【问题标题】:Python BeautifulSoup html.parser not workingPython BeautifulSoup html.parser 不工作
【发布时间】:2019-02-17 15:31:10
【问题描述】:

我有一个脚本可以从亚马逊提取图书信息,该脚本之前运行成功,但今天失败了。我无法弄清楚到底出了什么问题,但我假设它与解析器或 Javascript 相关。我正在使用下面的代码。

from bs4 import BeautifulSoup
import requests

response = requests.get('https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Dstripbooks&field-keywords=9780307397980',headers={'User-Agent': b'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'})
html = response.content
soup = BeautifulSoup(html, "html.parser")
resultcol = soup.find('div', attrs={'id':'resultsCol'})

以前我在resultcol 中获取数据,但现在它是空白的。当我检查html 时,我看到了我正在寻找的标签,即<div id="resultsCol" class=\'\' >。但是soup 里面没有这个文本。谁能帮我调试一下?以前可以正常工作,但现在不行了。

【问题讨论】:

  • 这很奇怪!我运行了这段代码,但我省略了标题,因为我使用请求已经有一段时间了,而且我不记得所有的规范。一切似乎都运行良好!也许尝试在不通过标头 kwarg 的情况下运行它?您的标题可能有一些错误。
  • 还是不行。标题似乎很好。我在“html”元素中得到了正确的信息。 'soup' 没有捕捉到所有的代码。

标签: javascript python beautifulsoup html-parsing


【解决方案1】:

您需要等到页面完全加载完毕。您必须使用phantomJs 来确保页面加载正确。

我能够使用以下代码获得正确的元素。

import requests
from bs4 import BeautifulSoup
from selenium import webdriver

url = ("https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3D"
       "stripbooks&field-keywords=9780307397980")

browser = webdriver.PhantomJS()
browser.get(url)
html = browser.page_source
soup = BeautifulSoup(html, 'lxml')
resultcol = soup.find('img', attrs={'class': 's-access-image'})
print resultcol

【讨论】:

  • 通过这个方法得到的结果和我在chrome的view-source看到的不一样。我脚本的另一部分需要找到以keywords=9780307397980for url in resultcol.find_all('a'): if url['href'].endswith('keywords='+str(ISBN_search)): if 'dp' in url['href']: sub_link.append(url['href']) linklist[link_search - 1] = url['href'] break结尾的链接
  • @NeilS 您可以在此处细化元素搜索。
  • 我无法找到包含该元素的 URL。我可以在 Chrome 上看到它,但在 soup 中看不到
  • @NeilS 检查所需元素的更新代码。您将需要一个正则表达式来获取 URL。
  • 对不起,如果我之前不清楚,但我正在脚本中寻找这个链接:https://www.amazon.com/Year-Flood-MaddAddam-Trilogy/dp/030739798X/ref=sr_1_1?ie=UTF8&qid=1536785536&sr=8-1&keywords=9780307397980....如果你在chrome上打开链接https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Dstripbooks&field-keywords=9780307397980并查看源代码(ctrl+u) 并转到第 1419 行(不知道对你来说是否一样),我可以看到这个链接。在我们刚刚解析的soup 中,我看不到这部分。知道为什么吗?
【解决方案2】:

删除标题,它应该可以工作。

from bs4 import BeautifulSoup
import requests
response = requests.get('https://www.amazon.com/s/ref=nb_sb_noss?url=search-    alias%3Dstripbooks&field-keywords=9780307397980')
html = response.content
soup = BeautifulSoup(html, "html.parser")
resultcol = soup.find('div', attrs={'id':'resultsCol'})`

【讨论】:

  • 我收到此错误AttributeError: 'bytes' object has no attribute 'parser'
  • "AttributeError: 'NoneType' object has no attribute 'foo' - 这通常是因为您调用 find() 然后尝试访问结果的 .foo` 属性。但在您的情况下, find() 没有找到任何东西,所以它返回 None,而不是返回标签或字符串。你需要弄清楚为什么你的 find() 调用没有返回任何东西。来自 BS4 文档
  • 我认为问题出在“div”上
猜你喜欢
  • 2016-07-11
  • 2018-08-26
  • 2021-06-16
  • 2020-11-21
  • 2016-10-22
  • 1970-01-01
  • 2017-08-11
  • 2019-11-22
  • 1970-01-01
相关资源
最近更新 更多