Python scraper在某些子域上不返回完整的html代码



我正在拼凑一个沃尔玛评论抓取器,它目前从大多数沃尔玛页面抓取html没有问题。当我尝试抓取评论页面时,它只会返回一小部分页面代码,主要是评论的文本和一些错误的标签。有人知道是什么问题吗?

import requests
headers = {
'Accept': '*/*',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36',
'Accept-Language': 'en-us',
'Referer': 'https://www.walmart.com/',
'sec-ch-ua-platform': 'Windows',
}
cookie_jar = {
'_pxvid': '35ed81e0-cb1a-11ec-aad0-504d5a625548',
}
product_num = input('Enter Product Number: ')
url2 = ('https://www.walmart.com/reviews/product/'+str(product_num))
r = requests.get(url2, headers=headers, cookies=cookie_jar, timeout=5)
print(r.text)

正如larsks已经评论过的那样,有些内容是动态加载的,例如,如果向下滚动足够远。BeautifulSoup或请求不会加载整个页面,但您可以使用Selenium解决这个问题。

Selenium的作用是在脚本控制的web浏览器中打开您的url,它允许您填写表单并向下滚动。下面是如何在BS4中使用Selenium的代码示例。

from bs4 import BeautifulSoup
from selenium import webdriver
# Search on google for the driver and save it in the path below
driver = webdriver.Firefox(executable_path="C:Program Files (x86)geckodriver.exe")
# for Chrome it's: driver = webdriver.Chrome("C:Program Files (x86)chromedriver.exe")
# Here you open the url with the reviews
driver.get("https://www.example.com")
driver.maximize_window()
# This function scrolls down to the bottom of the website
driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
# Now you can scrape the given website from your Selenium browser using:
html = driver.page_source
soup = BeautifulSoup(html)

此解决方案假设通过向下滚动页面加载评论。当然,你不必使用BeautifulSoup来抓取站点,这是个人喜好。如果有帮助,请告诉我。

最新更新