【问题标题】:How do I get a header with a python web scraper?如何使用 python 网络爬虫获取标题?
【发布时间】:2021-10-28 22:17:42
【问题描述】:

所以我在为我正在开发的网站制作的网络爬虫时遇到问题。我遇到的主要问题是,当尝试获取 h1 格式的产品的标题时,它会不断响应: <h1 class="product-detail__title small-title">CHERRY MX SILENT RED(10pcs)</h1> 我只想要 Cherry Mx Silent Red 部分,而不是所有其他东西。 这是我的网络爬虫的代码:

from bs4 import BeautifulSoup

URL = 'https://kbdfans.com/collections/cherry-switches/products/cherry-mx-silent-red'

headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}

page = requests.get(URL, headers=headers)

soup = BeautifulSoup(page.content, 'html.parser')

title = soup.find('h1', {'class' : 'product-detail__title small-title'})

print(title)

【问题讨论】:

    标签: html web-scraping beautifulsoup


    【解决方案1】:

    试试这个:

    title.get_text()
    

    你的标题不是一个字符串,它是一个对象

    来自 BeautifulSoup 文档:

    The find_all() method looks through a tag’s descendants and retrieves all descendants that match your filters.

    对于您的 title 变量,您可以参考 bs4.element.Tag 文档,如果您有疑问,您可以随时打印该对象的所有可用方法,如下所示:

    print(dir(title))
    

    【讨论】:

    • 这是正确的吗? title = soup.get_text('h1', {'class' : 'product-detail__title.small-title'})
    • 您在问题中分享的代码是可以的,您只需在您的标题对象上调用 get_text() 函数,它不需要任何参数,只需通过以下方式更改您的最后打印:“print( title.get_text())" 有关 get_text 的更多文档:crummy.com/software/BeautifulSoup/bs4/doc
    • 好吧,这就是我得到的结果Traceback (most recent call last): File "C:\Users\redoc\Documents\GitHub\KeeBuilderRepo\webscraper.py", line 14, in <module> print(title.get_text()) AttributeError: 'str' object has no attribute 'get_text'
    • Mm 适合我,你的美汤版本是什么?
    • 我怎样才能找到它?
    【解决方案2】:

    当您需要将自定义参数传递给 strip 空格时,只需使用 .text.get_text() 从您的 <h1> 获取文本,...或添加分隔符(例如 title.get_text(strip=True, seperator=','))。

    print(title.text)
    

    print(title.get_text())
    

    示例

    from bs4 import BeautifulSoup
    
    URL = 'https://kbdfans.com/collections/cherry-switches/products/cherry-mx-silent-red'
    
    headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    
    page = requests.get(URL, headers=headers)
    
    soup = BeautifulSoup(page.content, 'html.parser')
    
    title = soup.find('h1', {'class' : 'product-detail__title small-title'})
    
    print(title.text)
    

    输出

    CHERRY MX SILENT RED(10pcs)
    

    【讨论】:

      猜你喜欢
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      相关资源
      最近更新 更多