社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何使用python web scraper获取标题?

MrSirDolphin • 4 年前 • 1888 次点击  

因此,我有一个问题,我的网站刮板我正在开发。我遇到的主要问题是,当试图为h1格式的产品获取标题时,它会不断响应: <h1 class="product-detail__title small-title">CHERRY MX SILENT RED(10pcs)</h1> 我只想要樱桃Mx无声的红色部分,而不是所有其他的东西。 以下是我的网络刮板的代码:

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)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133624
文章 [ 2 ]  |  最新文章 4 年前
HedgeHog
Reply   •   1 楼
HedgeHog    5 年前

从你的 <h1> 使用 .text 和 .get_text() 当需要将自定义参数传递给 strip 空格,。。。或者添加一个分隔符(例如。 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)
Ram mysterymachines
Reply   •   2 楼
Ram mysterymachines    5 年前

试试这个:

title.get_text()

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

从BeautifulSoup文档:

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

为了你的 标题 变量,您可以参考bs4。要素标记文档,如果您有疑问,可以随时打印该对象的所有可用方法,如下所示:

print(dir(title))