【问题标题】:Python Web Scraping | How to scrape data from multiple urls by choosing page number as a range with Beautiful Soup and selenium?Python 网页抓取 |如何通过选择页码作为 Beautiful Soup 和 selenium 的范围从多个 url 中抓取数据?
【发布时间】:2021-11-15 02:49:20
【问题描述】:
from selenium import webdriver
import time
from bs4 import BeautifulSoup as Soup
driver = webdriver.Firefox(executable_path='C://Downloads//webdrivers//geckodriver.exe')
a = 'https://www.amazon.com/s?k=Mobile&i=amazon-devices&page='
for c in range(8):

    #a = f'https://www.amazon.com/s?k=Mobile&i=amazon-devices&page={c}'

    cd = driver.get(a+str(c))

    page_source = driver.page_source
    bs = Soup(page_source, 'html.parser')

    fetch_data = bs.find_all('div', {'class': 's-expand-height.s-include-content-margin.s-latency-cf-section.s-border-bottom'})

    for f_data in fetch_data:
        product_name = f_data.find('span', {'class': 'a-size-medium.a-color-base.a-text-normal'})
        print(product_name + '\n')

现在的问题是,Webdriver 成功访问了 7 个页面,但没有提供任何输出或错误。

现在我不知道 M 哪里出错了。

欢迎任何建议,参考提供有关此问题的解决方案的文章。

【问题讨论】:

    标签: python selenium-webdriver web-scraping beautifulsoup


    【解决方案1】:

    您没有选择正确的 div 标签来使用 BeautifulSoup 获取产品,导致没有输出。

    试试下面的 sn-p:-

    #range of pages
    for i in range(1,20):
    
        driver.get(f'https://www.amazon.com/s?k=Mobile&i=amazon-devices&page={i}')
        page_source = driver.page_source
        bs = Soup(page_source, 'html.parser')
        
        #get search results
        products=bs.find_all('div',{'data-component-type':"s-search-result"})
    
        #for each product in search result print product name
        for i in range(0,len(products)):
            for product_name in products[i].find('span',class_="a-size-medium a-color-base a-text-normal"):
                print(product_name)
    

    【讨论】:

    • 嘿,代码有效,你能建议我如何获得班级的 div 吗?我所学到的是,如果您选择一个框,并且当最后出现绿色边框时,您会找到该 div。
    • products=bs.find_all('div',{'data-component-type':"s-search-result"})这是获取页面上每个产品的div的部分,您获取div标签的方法是正确的,但是当有嵌套的div时要小心
    • 那么嵌套的 div 应该怎么做呢?你能给我推荐一个嵌套div的例子吗?所以我的概念变得更加清晰
    • This 链接可能有用
    • 感谢您的帮助,只是想最后一个建议,因为您知道搜索页面和产品页面是不同的。有没有办法可以找到产品页面的数据,例如库存等。我不想要解决方案,我只想要一些步骤。
    【解决方案2】:

    可以打印 bs 或 fetch_data 进行调试。

    不管怎样

    在我看来,您可以使用requestsurllib 来获取page_source 而不是selenium

    【讨论】:

    • 你能提供任何例子吗?
    • @Mathues Torquato 即使我想要那个例子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 2015-08-28
    • 1970-01-01
    相关资源
    最近更新 更多