【问题标题】:BeautfulSoup findAll not returning resultsBeautifulSoup findAll 不返回结果
【发布时间】:2021-11-21 22:13:03
【问题描述】:

我想在此页面上获取产品名称和价格。我几乎重复了我为价格的产品名称所做的完全相同的事情,但我没有得到任何东西。

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as bSoup

header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:77.0) Gecko/20100101 Firefox/77.0'}
url = "https://www.walmart.ca/search?q=lettuce"
req = Request (url = url, headers = header)

client = urlopen (req)
pageHtml = client.read()
client.close()

pageSoup = bSoup(pageHtml, 'html.parser')

products = pageSoup.findAll ("div", {"class":"css-155zfob e175iya63"})
print (len(products)) #prints 15, like expected
for product  in products:
    pass

prices = pageSoup.findAll ("div", {"class":"css-8frhg8 e175iya65"})
print (len (prices))#prints 0 and idk why :/
for price in prices:
    pass

【问题讨论】:

  • 请发布minimal reproducible example 特别是导入语句,以便我们运行您的代码。您是否看到“抱歉,此网页需要 JavaScript 才能正常运行。”?
  • 我添加了导入语句。不,我没有看到那条消息。我运行这个程序时的输出只是 15 和 0
  • 您可以print(pageHtml) 查看原始内容。不确定我们还能为您做些什么。如果有用请采纳。

标签: python python-3.x beautifulsoup urllib


【解决方案1】:

页面https://www.walmart.ca/search?q=lettuce没有返回你期望的内容:

curl -s -H 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:77.0) Gecko/20100101 Firefox/77.0' 'https://www.walmart.ca/search?q=lettuce' | grep 'css-8frhg8'

您可能在浏览器中看到了该类,其中内容在运行时通过 JavaScript 部分呈现。这意味着您需要使用可以模拟支持 JavaScript 的浏览器的库。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 2019-02-26
    • 1970-01-01
    相关资源
    最近更新 更多