Python BeautifulSoup4 WebCrawler .findAll() 未解析

Python BeautifulSoup4 WebCrawler .findAll() not parsing

全部!

我正在尝试制作一个 python 网络抓取工具以从零售网站中提取所有产品名称。执行此操作的代码(在 PyCharm 中)如下:

import requests
from bs4 import BeautifulSoup

def louis_spider(max_pages):
    page = 0
    while page <= max_pages:
            url = 'https://us.testcompany.com/eng-us/women/hanbags/_/N-r4xtxc/to-' + str(page)
            source_code = requests.get(url)
            plain_text = source_code.text
            soup = BeautifulSoup(plain_text, 'html.parser')
            for eachItem in soup.findAll('main', {'class': 'content'}):
               printable = eachItem.get('id')
               print(printable)
               print('Test1')
            page += 1

louis_spider(0)

因为它目前是(上图),代码不打印任何东西 - 甚至 "Test1." 我已经 运行 这与 .findAll()&.get() 中的其他输入运气好的方法: .findAll('a', {'class':'skiplinks'})and.get('href') 生成了“#content Test1”,.findAll('div', {'id':'privateModeMessage'})and.get('style') 生成了 'display:none Test1'。这是网站上的 'inspect element' 代码的一部分,供您参考:

a snippet of the website's code, providing context for my mentioned attempts which worked

不幸的是,我上面的代码块没有产生任何结果!当我尝试引用 <main> 部分中的项目时,问题似乎出现了 - 我在引用直到它的行时得到了结果。理想情况下,我将能够提取网页上每个项目的名称(请参阅网站代码的另一个快照,以特定参考网站中的相关行)。这些行在网站代码的 <main> 部分内,所以我怀疑我的 for 循环从未在此处输入,原因与它不在 <main> 内的任何其他行一样,就像在我上面的街区... the way I'd write this is .findAll('a', {'class': 'productName'}): and .get('class')

也就是说,我找不到 <main> 中的内容无法被 BeautifulSoup 访问的原因。有谁知道为什么会这样?提前致谢!

根据您在评论中发布的代码,您得到的是一个空列表,因为您的 XPath 是错误的。 class productPricespan 标签内,而不是 div.

您可以通过这样做获得您想要的值:

namesElements = browser.find_elements_by_xpath("//span[@class='productPrice']")
names = []
[names.append(x.text) for x in namesElements]
print(names)