【发布时间】:2020-06-18 13:45:00
【问题描述】:
正在尝试从 nikes 网站上抓取网页进行练习,并将数据保存在 csv 文件中。它在将数据保存到文件方面工作得很好,但它只保存前 24 只鞋子(鞋子名称、价格、颜色等),即使我试图阅读的页面上有 50 多只鞋子。请注意,最初页面显示的鞋子较少,但随着我们继续向下滚动,它开始显示更多的鞋子,但即使最初它显示的鞋子也略多于 24 只。 这是我的第一个刮刀和我的第一个帖子,如果有不清楚的地方,我很抱歉,但感谢您的帮助。 谢谢
from urllib.request import urlopen
mylink = "https://www.nike.com/w/mens-soccer-shoes-1gdj0znik1zy7ok"
opened = urlopen(mylink)
read = opened.read()
opened.close()
page = soup(read, "html.parser")
containers = page.findAll("div", {"class":"product-card__info"})
file = open("nike.csv" , "w")
headers = "Name , Type, Colors, Price \n"
file.write(headers)
for container in containers:
namecontainer = container.findAll("div", {"class": "product-card__title"})
name = namecontainer[0].text
typecontainer = container.findAll("div", {"class": "product-card__subtitle"})
type = typecontainer[0].text
colors = container.findAll("div", {"class": "product-card__count-wrapper"})
no_of_colors = colors[0].button.div.text
pricecontainer = container.findAll("div", {"data-test": "product-price"})
price = pricecontainer[0].text
print("name: " + name)
print("type: " + type)
print("colors: " + no_of_colors )
print("price : " + price + "\n")
file.write(name.replace(",","|") + "," + type.replace(",","|") + "," + no_of_colors + "," + price + "\n)```
【问题讨论】:
-
问题在于网站的设置方式。滚动前不可见的鞋子的 div 元素也不在页面的 html 文档中。它们在滚动后出现。因此,您需要先模拟滚动,然后才能从 html 文档中读取它们。也许查看selenium,这将允许您在搜索 div 之前滚动到页面底部。
标签: python python-3.x web-scraping beautifulsoup