-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscraper.py
95 lines (46 loc) · 1.34 KB
/
scraper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python
# coding: utf-8
# ## Scrape the Houston NPR website
#
# https://www.houstonpublicmedia.org/
#
# I want a CSV file called `npr.csv` that includes a row for each story in the top section, with these columns:
#
# * `section`, the section of the story (e.g. "Transportation", "Harris County")
# * `title`, the title of the story
# * `url`, the full URL to the story
#
# If you want to start by printing these out, that's fine, but the end result is hopefully a CSV. If you'd like to filter out the rows without a title before saving that would be nice.
# In[22]:
import requests
from bs4 import BeautifulSoup
response = requests.get("https://www.houstonpublicmedia.org/")
doc = BeautifulSoup(response.text)
# In[23]:
len(doc.find_all('article'))
# In[24]:
len(doc.find_all(class_='post'))
# In[25]:
for story in doc.find_all('article'):
print(story.text.strip())
# In[26]:
stories = doc.find_all(class_='post')
# In[27]:
stories = doc.select('.post')
# In[28]:
dataset = []
for story in stories:
data = {}
data['section'] = story.find('h3').text
data['title'] = story.find('h2').text
data['url'] = story.find('a')['href']
dataset.append(data)
dataset
# In[29]:
import pandas as pd
df = pd.DataFrame(dataset)
df.head()
# In[30]:
df.to_csv("npr.csv", index=False)
# In[ ]:
# In[ ]: