【问题标题】:Using Python Beautiful soup for Web scrape使用 Python Beautiful soup 进行 Web 抓取
【发布时间】:2020-11-19 17:41:59
【问题描述】:

我希望从以下网页中提取 ASIN 编号。 ASIN 编号遵循亚马逊上 HTML 的“data-asin”元素。然后我想以与下面的其他元素相同的方式打印输出。提前感谢您的帮助

import csv
from bs4 import BeautifulSoup
from selenium import webdriver

path = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(path)

def get_url(search_term):
    """Generate a url from search term"""
    template = 'https://www.amazon.co.uk/s?k={}&ref=nb_sb_noss_2'
    search_term = search_term.replace(' ','+') 
    return template.format(search_term)

url = get_url('Ultrawide monitor')

driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
results = soup.find_all('div',{'data-component-type': 's-search-result'})

item = results [0]

atag = item.h2.a
atag.text
description = atag.text.strip()
url = 'https//www.amazon.com'+atag.get('href')
price_parent = item.find('span', 'a-price')
price = price_parent.find('span', 'a-offscreen').text
rating = item.i.text
review_count = item.find('span', {'class': 'a-size-base', 'dir':     
'auto'}).text

print(description)
print(price)
print(rating)
print(review_count)

【问题讨论】:

  • 什么是 ASIN 编号?你得到的错误到底是什么?此代码在results = soup.find_all('div',{'data-component-type': 's-search-result'}) 行之后似乎不起作用。
  • 这似乎对我有用....所以不知道为什么。 ASIN 号是产品代码
  • 啊..所以你想点击搜索列表中的每个项目来获取 ASIN、描述等?
  • ASIN 在网站的 HTML 中。或在“项目”对象中。我可以看到 data-asin="B08BYJ5BCF" 它是我需要的语音标记中的参考
  • 这是什么? atag.text ..这无济于事。您想将其分配给变量吗?

标签: python web-scraping beautifulsoup


【解决方案1】:

问题描述有待改进 - 据我了解,您希望获得h2link text

解决方案

from bs4 import BeautifulSoup
html_doc ='''
<div class="a-section a-spacing-none">
    <h2 class="a-size-mini a-spacing-none a-color-base s-line-clamp-2">
        <a class="a-link-normal a-text-normal" href="/Promised-Land-Barack-Obama/dp/0241491517/ref=sr_1_1?dchild=1&amp;keywords=%7B%7D&amp;qid=1605860574&amp;sr=8-1">
            <span class="a-size-medium a-color-base a-text-normal" dir="auto">A Promised Land</span>
        </a>
    </h2>
    <div class="a-row a-size-base a-color-secondary"><span class="a-size-base" dir="auto">by </span>
        <a class="a-size-base a-link-normal" href="/Barack-Obama/e/B001H6OA8E?ref=sr_ntt_srch_lnk_1&amp;qid=1605860574&amp;sr=8-1">
            Barack Obama
        </a>
    <span class="a-letter-space"></span><span class="a-size-base a-color-secondary" dir="auto"> | </span><span class="a-letter-space"></span><span class="a-size-base a-color-secondary a-text-normal" dir="auto">17 Nov 2020</span></div>
</div>
'''
soup = BeautifulSoup(html_doc, 'html.parser')

选择h2中的a

atag = soup.select('h2 > a')
print(atag[0].text)

希望这对您有所帮助 - 让我们知道或尝试更详细地描述您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2020-11-23
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多