gpt4 book ai didi

python - 使用 Xpath 在 python 中抓取问题

转载 作者:太空宇宙 更新时间:2023-11-03 15:43:52 25 4
gpt4 key购买 nike

我正在努力铲除在这件事上犯下的所有罪行webpage 。我想要抓取的每个页面的格式都是“http://www.mylocalcrime.com/#”+邮政编码。然而,当我通过 python 或 Chrome 查看源代码时,我没有得到任何列出逮捕的数据。我得到一个通用网页,其中包含每种犯罪类型的图片以及该犯罪的标签。例如,来源会说(您可以通过查看来源看到这一点): li <...>破坏行为/li> 但破坏行为不是犯罪,它只是一个具有破坏内容的通用破坏符号。

我尝试过使用美丽的汤,我的代码基本上是:

import csv
from bs4 import BeautifulSoup
from lxml import html
import requests

csvloc = '.../.../filelocation.csv'

ziplist = [1001]
listofcrimes = []

#with open(csvloc,'r') as csvfile:
# ziplist = list(csv.reader(csvfile))

for each in ziplist:
zipcode = str(each).zfill(5)
page = requests.get('http://www.mylocalcrime.com/#'+zipcode)
tree = html.fromstring(page.content)

此请求返回通用页面的 html 文件。一定有办法做到这一点,因为当我使用桌面抓取工具时,它会抓取结果并提供 Xpath://tr[50]/td([] 从 0 到 50)。不太了解 Xpath,但我读到的源文件中没有 tr。如有帮助,将不胜感激。

最佳答案

关闭浏览器中的 JavaScript 并再次加载页面 - 您会看到空白页面。

页面上的所有数据都是通过 JavaScript 和 AJAX 添加的。

lxmlBS 不执行 JavaScript,因此您无法找到此数据。

您可以使用Selenium(或类似工具)来控制浏览器加载页面并运行JavaScript,然后您可以获得包含所有数据的HTML。

或者使用 Chrome/Firefox 中的 DevTools 查看 JavaScript 使用哪个 url 来读取此数据,然后您可以使用 requests 从此 url 读取数据。 JavaScript主要读取JSON格式的数据,更容易搜索数据。

<小时/>

编辑:它使用 API http://api.spotcrime.com获取数据。

它可能需要服务器上的帐户 http://spotcrime.com并拥有私钥来获取数据。

来自 http://www.mylocalcrime.com 的示例链接它以 JSON 形式提供数据:

http://api.spotcrime.com/crimes.json?lat=0&lon=0&radius=0.04&key=privatekeyforspotcrimepublicusers-commercialuse-877.410.1607

<小时/>
import requests

url = 'http://api.spotcrime.com/crimes.json?lat=0&lon=0&radius=0.04&key=privatekeyforspotcrimepublicusers-commercialuse-877.410.1607'

r = requests.get(url)

data = r.json()

crimes = data['crimes']

for x in crimes:
print(x['type'], x['date'])

结果:

Arrest 01/26/17 03:38 PM
Arrest 01/21/17 09:30 PM
Arrest 01/20/17 05:09 PM
Other 01/16/17 07:50 PM
Arrest 01/16/17 11:14 AM
Assault 01/15/17 07:59 AM
Arrest 01/12/17 02:27 PM
Assault 01/09/17 10:45 PM
Theft 01/09/17 12:33 PM

关于python - 使用 Xpath 在 python 中抓取问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41927568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com