Python 使用BeautifulSoup,网页抓取仅获得一半的项目

Python 使用BeautifulSoup,网页抓取仅获得一半的项目,python,web-scraping,beautifulsoup,Python,Web Scraping,Beautifulsoup,我正试图从第页获得所有文章的标题 我想要的所有84项都具有相同的类名: “cat_品牌名称-2XZRz cat_省略号-MujnT” 这是我的密码 from bs4 import BeautifulSoup import urllib url = "https://www.zalando.nl/herenschoenen/" soep = BeautifulSoup(urllib.request.urlopen(url).read(), 'lxml') #trying to get al

我正试图从第页获得所有文章的标题

我想要的所有84项都具有相同的类名:

“cat_品牌名称-2XZRz cat_省略号-MujnT”

这是我的密码

from bs4 import BeautifulSoup
import urllib


url = "https://www.zalando.nl/herenschoenen/"

soep = BeautifulSoup(urllib.request.urlopen(url).read(), 'lxml')

#trying to get all objects with the article tag, which should be 84 items.
articles = (soep.body.find_all("article"))


for x in articles:
    try:
        print(x.find(class_="cat_brandName-2XZRz cat_ellipsis-MujnT").get_text())
    except:
        continue
但结果只给了我84项中的35项:

Nike Sportswear
Nike Sportswear
Nike Performance
Nike Performance
adidas Originals
Nike Sportswear
Clarks Originals
Nike Sportswear
Nike Performance
Nike Sportswear
Nike Sportswear
Nike Sportswear
Puma
Lacoste
Clarks Originals
Vans
Nike Performance
Birkenstock
adidas Originals
adidas Originals
Reef
adidas Originals
New Balance
Nike SB
Levi's®
adidas Originals
Lacoste
Tommy Hilfiger
New Balance
Reebok Classic
Bugatti
Birkenstock

当我将网页作为Chrome HTML文档保存到我的设备中,并在代码中使用它时,它会工作,我会得到所有的文章标题

但是我不想下载这些页面,也许有一种方法可以使用urllib来完成。
(对于requests.get(),这是同样的问题)

使用API可能是解决此问题的最佳方法,但是您也可以借助selenium来实现这一点。你没有得到所有结果的原因是,当你第一次打开网页时,没有加载网页中的所有内容。确保您安装了ChromiumWebDriver并将其放在您的路径中

从selenium导入webdriver
从bs4导入BeautifulSoup
url=”https://www.zalando.nl/herenschoenen/"
driver=webdriver.Chrome(driverPath)
获取驱动程序(url)
html\u content=driver.execute\u脚本('returndocument.body.innerHTML')
soep=BeautifulSoup(html_内容“lxml”)
articles=(soep.body.find_all(“article”))
对于文章中的x:
尝试:
打印(x.find(class=“cat_brandName-2XZRz cat_ellission-MujnT”).get_text())
除:
持续

使用API可能是解决此问题的最佳方法,不过您也可以借助于
selenium
来实现这一点。你没有得到所有结果的原因是,当你第一次打开网页时,没有加载网页中的所有内容。确保您安装了ChromiumWebDriver并将其放在您的路径中

从selenium导入webdriver
从bs4导入BeautifulSoup
url=”https://www.zalando.nl/herenschoenen/"
driver=webdriver.Chrome(driverPath)
获取驱动程序(url)
html\u content=driver.execute\u脚本('returndocument.body.innerHTML')
soep=BeautifulSoup(html_内容“lxml”)
articles=(soep.body.find_all(“article”))
对于文章中的x:
尝试:
打印(x.find(class=“cat_brandName-2XZRz cat_ellission-MujnT”).get_text())
除:
持续

我没有使用过Beutiful Soup,但根据您的说法,以交互方式保存网页的内容比从Beautiful Soup下载的网页的内容要多。我认为,也许页面在使用Javascript从服务器初始下载后添加了内容。如果不使用浏览器,很难清除非静态页面。Selenium测试框架允许您等待页面中出现某些项目,因为它可以与正在运行的web浏览器交互。我没有使用Beutiful Soup,但从您所说的,以交互方式保存网页的内容比从Beautiful Soup下载的页面的内容要多。我认为,也许页面在使用Javascript从服务器初始下载后添加了内容。如果不使用浏览器,很难清除非静态页面。Selenium测试框架允许您等待某些项目出现在页面中,因为它可以与正在运行的web浏览器进行交互。这对我很有用,谢谢。现在我也很好奇什么是API以及如何使用它。这对我很有用,谢谢。现在我也很好奇API是什么,以及如何使用它。