【问题标题】:Scraping data-page attributes from web page从网页中抓取数据页属性
【发布时间】:2022-01-21 14:43:41
【问题描述】:

我想从这个网站上刮掉所有没有分页按钮的产品。滚动时会自动加载产品。我的脚本只能抓取前 40 个产品。我意识到产品在 div 标签的数据页属性中动态加载? ? 我希望我的脚本不断更改数据页值并加载产品,但我不知道该怎么做。

from bs4 import BeautifulSoup
import requests
import pandas as pd
import time

url = 'https://www.positivepromotions.com/custom-blankets/c/navpp_1001_114/'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'}
result = requests.get(url, headers=headers, timeout=5000)
data = result.content.decode()
soup1 = BeautifulSoup(data,'lxml')
## get the category
## get the conbtainer first container
subcategory = soup1.find('h1').text.strip()

itemlist = []
for soup in soup1.find_all('div', class_='row cat-prod-list'):
    for x in range(1,4):
        #for pages in soup.find_all('div', id='categoryProducts', attrs={'data-page': True}):
        for pages in soup.select('div[data-page]', id='categoryProducts'):
            print(pages['data-page'])
            for productList in pages.find_all('div', class_='col-sm-4 col-md-3 cat-prod-container'):
              title = productList.find('a', class_='product-title').text.strip()
              price = productList.find('span', class_='cat-price').text.strip().split('-',1)[0]
              sku = productList.find('div', class_='grid-prod-sku').text.strip()
              #productlist = soup.find_all('div', class_='prod-img-wrap')
              links = productList.find('a', class_='cat-prod-img',href=True)['href']
              image = productList.find('img')['data-src'].split('?',1)[0]

              items = {
                      'Title': title,
                      'Price': price,
                      'Sku': sku,
                      'Category': subcategory,
                      'Link': links,
                      'Image': image
                  }
              itemlist.append(items)
              ##print('Saving : ',title)
              #time.sleep(1)
            
# print total products found
print(len(itemlist))

#df = pd.DataFrame(itemlist)
##print(df.head(5))
#df.to_csv(subcategory+'.csv')
###

【问题讨论】:

  • 尝试使用selenium加载页面并在捕获数据之前滚动。

标签: python web-scraping beautifulsoup


【解决方案1】:

我认为最好的方法是使用Selenium 库。它非常易于使用,因此不必担心实施。 你需要:

  1. 安装它
  2. 创建您的 selenium 驱动程序(最好是 chrome 驱动程序)
  3. 导航到网址
  4. 通过 XPath 获取数据(文档中已经提到)
  5. 滚动到最后一个产品以自动加载页面

最后一步使用this

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 2021-10-15
    • 2021-12-28
    • 2019-01-18
    • 2012-04-22
    • 2020-06-18
    相关资源
    最近更新 更多