我想从这个网站自动保存城市的数据:
我使用beautifulsoup
库从网页中获取数据。
http://open.dataforcities.org/details?4[]=2016
import urllib2
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen('http://open.dataforcities.org/details?4[]=2016').read())
如果我遵循用Python进行Web抓取中的示例,就会得到以下错误:
soup = BeautifulSoup(urllib2.urlopen('http://example.com').read())
for row in soup('table', {'class': 'metrics'})[0].tbody('tr'):
tds = row('td')
print tds[0].string, tds[1].string
IndexError Traceback (most recent call last)
<ipython-input-71-d688ff354182> in <module>()
----> 1 for row in soup('table', {'class': 'metrics'})[0].tbody('tr'):
2 tds = row('td')
3 print tds[0].string, tds[1].string
IndexError: list index out of range
[1]: http://www.dataforcities.org/
[2]: http://open.dataforcities.org/
[3]: https://i.stack.imgur.com/qfQyG.png
发布于 2018-01-18 02:22:25
通过快速查看站点,这个站点的一个很好的技术就是查看页面上JS提出的请求。它将显示用于收集页面上填充的数据的内部API。
例如,对于特定的城市,会向http://open.dataforcities.org/city/109/themes/2017
发出GET请求,该请求包含包含多个条目的JSON响应。您可以使用requests
自己获得这个
>>> import requests
>>> response = requests.get('http://open.dataforcities.org/city/109/themes/2017')
>>> response.json()
[{'theme': 'Economy', 'score': 108, 'date': '2015', 'rank': '2/9'}, {'theme': 'Education', 'score': 97, 'date': '2015', 'rank': '8/9'}, {'theme': 'Energy', 'score': 110, 'date': '2015', 'rank': '1/9'},
因此,只需做一点点工作,您就可以发现获取所需数据所需的所有端点。这只是一个方法。您还可以使用浏览器自动化工具(如selenium
) --不仅用于自动滚动和单击浏览器操作,还可以执行任意JavaScript并检查js中的数据。
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://example.com/page/to/scrape')
value = driver.execute_script('return someThing.value;')
但是,在尝试抓取站点时遇到很多麻烦之前,您应该始终检查它们是否有您可以使用的有文档的公共API。
发布于 2018-01-18 02:21:52
您可以使用Python、Beautifulsoup库从网站上抓取数据,帮助清理html代码和提取。它们也是其他图书馆。甚至NodeJs也可以这样做。
主要是你的逻辑。Python和Beautifulsoup将为您提供数据。你必须分析并保存在数据库中。
其他请求,lxml,Selenium,Scrapy
示例
from bs4 import BeautifulSoup
import requests
page = requests.get("http://www.dataforcities.org/")
soup = BeautifulSoup(page.content, 'html.parser')
all_links = soup.find_all(("a")
就像上面一样你能找到任何东西。有许多功能。教程web抓取教程
最好也检查一下官方文件。
https://stackoverflow.com/questions/48318730
复制