【问题标题】:Selenium how to count and keep track of the number of productsSelenium 如何统计和跟踪产品的数量
【发布时间】:2021-07-13 00:11:32
【问题描述】:

我正在尝试在给定关键字/search_term 时抓取产品的数据,到目前为止,我已经设法抓取了从第一页到最后一页的所有数据。

但是,我想改变它,只抓取前 100 或 150 个我不知道该怎么做的产品。

我认为我需要一些整数值来跟踪我正在抓取的项目数量,并在整数达到 100 或 150 时停止。

我知道我需要更改“for page in range (1, last_page)”上的某些内容,但我已经尝试并最终为每个项目获得了 100 个相同的结果,这不是我应该做的去做。

def main(search_term):
    # RUN MAIN PROGRAM ROUTINE
    chromedriver = "path to chromedriver"
    driver = webdriver.Chrome(chromedriver)
    
    records = []
    url = get_url(search_term)
    
    driver.get(url)
    last_page = int(driver.find_element_by_xpath('(//div[@class="a-text-center"]/ul/li)[last()-1]').text) + 1
    
    # NUMBER OF PAGES TO CRAWL
    for page in range(1, last_page):
        driver.get(url.format(page))
        soup = BeautifulSoup(driver.page_source, 'html.parser')
        results = soup.find_all('div', {'data-component-type': 's-search-result'})
        print(page)
        
        for item in results:
            record = extract_record(item)
            if record:
                records.append(record)
                        
    driver.close()

# Run the main function given a keyword
main("make-up")
# leads to https://www.amazon.com/s?k=cosmetics&ref=nb_sb_noss

#main("iphone")

我将如何继续更改它,以便我可以抓取前 100、150 或任何我想抓取的数字?

【问题讨论】:

  • @Arundeep Chohan 我最终还是会刮到最后一页,这不是我想要的
  • 哦,所以你想打破双 for 循环。

标签: python selenium for-loop web-scraping xpath


【解决方案1】:

所以你必须检查记录长度是否为 100,然后从外部 for 循环中中断。

for page in range(1, last_page):
    driver.get(url.format(page))
    soup = BeautifulSoup(driver.page_source, 'html.parser')
    results = soup.find_all('div', {'data-component-type': 's-search-result'})
    print(page)
    find=False
    for item in results:
        records.append(item)
        if len(records)==100:
            find=True
            break
    if find:
        break
            

【讨论】:

  • 当您更改了代码中的一些措辞时,我有点困惑,但我设法弄明白了!非常感谢!!
猜你喜欢
  • 1970-01-01
  • 2015-03-08
  • 2012-07-26
  • 1970-01-01
  • 2010-10-30
  • 2022-12-16
  • 1970-01-01
  • 1970-01-01
  • 2012-03-07
相关资源
最近更新 更多