如何使用beautifulsoup4用我的python脚本抓取更多亚马逊产品?

0-英雄

我有一个代码来获得 3 星及以上评级的前 20 名产品。我需要帮助为 2000 种产品创建一些东西。请检查我的代码。我正在考虑获取亚马逊网站上页码的链接并进行循环,直到获得 2000 件产品,但不知道如何进行循环。这是我的代码:

import requests
from bs4 import BeautifulSoup
import re
headers = {'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'}


def star_link():
    search = input("Please enter the category or search term: ")
    url1 = "https://www.amazon.in/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=" + search
    r1 = requests.get(url1)
    soup1 = BeautifulSoup(r1.text, 'lxml')
    links = soup1.find_all('i', 'a-star-3')
    for link in links:
        a_tag = link.parent
        a_link = a_tag['href']
    return a_link


def products():
    url2 = "https://www.amazon.in/"+star_link()
    r2  = requests.get(url2)
    soup2 = BeautifulSoup(r2.text, 'lxml')
    link_title = {}
    print('The top 2000 products of youe selected category with 3 stars and up are: ')
    print('\n')
    for n in range(0, 20):
        contents = soup2.findAll('li', id='result_' + str(n))
        for content in contents:
            links = [a['href'] for a in content.find_all(lambda i: i.get('href') and i.text)]
            titles = content.find_all('h2')
            for link in links:
                for title in titles:
                    link_title.update({title.text: link})
    for title in link_title:
        print(title + ':' + link_title[title])


products()
简单的

用于while True无限循环运行,break未获取数据时使用

    data = soup.select('.result-info')
    if not data:
        print('END: no data:')
        break

顺便提一句:

  • 即使您s=0在 url 中使用服务器也会提供第一页,因此您不必检查if i == 0
  • s={}可以在任何地方之后?- 所以它可以在最后使代码更具可读性
  • 你导入了csv模块,但你没有使用它。
    我使用它,我不需要,replace(","," ")因为" "如果,项目中文本,它会放入文本

完整代码

import requests
from bs4 import BeautifulSoup
import csv

filename = "output.csv"

f = open(filename, 'w', newline="", encoding='utf-8')

csvwriter = csv.writer(f)

csvwriter.writerow( ["Date", "Location", "Title", "Price"] )

offset = 0

while True:
    print('offset:', offset)

    url = "https://portland.craigslist.org/search/sss?query=xbox&sort=date&s={}".format(offset)

    response = requests.get(url)
    if response.status_code != 200:
        print('END: request status:', response.status)
        break

    soup = BeautifulSoup(response.text, 'html.parser')

    data = soup.select('.result-info')
    if not data:
        print('END: no data:')
        break

    for container in data:
        date = container.select('.result-date')[0].text

        try:
            location = container.select('.result-hood')[0].text
        except:
            try:
                location = container.select('.nearby')[0].text 
            except:
                location = ''
        #location = location.replace(","," ") # don't need it with `csvwriter`

        title = container.select('.result-title')[0].text

        try:
            price = container.select('.result-price')[0].text
        except:
            price = ''
        #title.replace(",", " ") # don't need it with `csvwriter`

        print(date, location, title, price)

        csvwriter.writerow( [date, location, title, price] )

    offset += 120

f.close()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在python 3.6中使用beautifulsoup4抓取网站以获取产品信息时

如何使用BeautifulSoup4使用Python修复Web抓取中的错误

使用beautifulsoup4后如何分离抓取结果?

使用 Python 抓取 HTML 中的特定元素:BeautifulSoup4

如何使用python和beautifulsoup4循环抓取网站中多个页面的数据

使用BeautifulSoup抓取亚马逊

无法使用BeautifulSoup4抓取网站

如何使用 Beautifulsoup4

如何使用BeautifulSoup4从客户标签中抓取信息

使用python + beautifulSoup4从动态图中抓取数据

使用python和Beautifulsoup4从抓取数据中写入和保存CSV文件

循环不适用于使用python和beautifulsoup4抓取数据

从抓取的数据中分割html(Python + BeautifulSoup4)

使用BeautifulSoup4进行数据抓取的问题

如何安装和使用beautifulsoup4

如何使用pd.DataFrame方法从使用beautifulsoup4抓取的信息中手动创建数据框

亚马逊使用bs4阻止了Python 3抓取

如何使用python中的BeautifulSoup库从具有“查看更多”选项的网站上抓取数据

我如何解析 <script type="text/javascript"> python beautifulsoup4

如何使用Beautifulsoup从网站上抓取产品价格?

用 Scrapy 抓取亚马逊

BeautifulSoup4抓取不能超过网站的第一页(Python 3.6)

Python 網頁抓取 youtube.com BeautifulSoup4 問題

如何使用beautifulsoup4在python中的pre标签中获取文本?

如何在Beautifulsoup4 for Python 3.6中使用soup.find()选择结果?

无法使用BeautifulSoup4(初学者)抓取正确的Wikitable

如何忽略BeautifulSoup4 Python上的标签

我正在尝试使用python3和beautifulsoup4为我的学校项目提取数据

如何使用 BeautifulSoup4 和请求获取标题的内容