【发布时间】:2018-09-02 19:17:35
【问题描述】:
全部!
我正在尝试制作一个 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”。这是网站上的“检查元素”代码的一部分,供您参考:
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 访问。有谁知道为什么会出现这种情况?提前致谢!
【问题讨论】:
-
页面是动态构建的。您无法使用
requests.get下载它。考虑使用selenium。 -
@DyZ,感谢您的意见!我正在使用 Selenium。我不能说你的回答解决了我的问题,因为我还没有让 Selenium 工作,但你似乎把我引向了正确的方向。所以 requests.get() 只适用于静态网页/网页部分?
-
@DyZ 我的新代码(使用 Selenium):
from selenium import webdriver chromePath = "/Users/Me/Documents/2018/chromedriver" browser = webdriver.Chrome(chromePath) url = 'https://us.louisvuitton.com/eng-us/women/handbags/_/N-r4xtxc/to-0' browser.get(url) namesElements = browser.find_elements_by_xpath("//div[@class='productPrice']") names = [] for x in namesElements: print('Test') names.append(x.text) print(names)仅产生“[]”的输出。看起来这并没有比我在原始帖子中的代码更好。 for 循环似乎没有被输入...
标签: python-3.x web-scraping beautifulsoup findall