首页 > 解决方案 > Python 网页抓取,使用 html-requests 查找特定元素并提取文本

问题描述

我正在使用 python 进行网页抓取(对此是新的),并试图从网站上获取品牌名称。它在网站上不可见,但我找到了它的元素:

<span itemprop="Brand" style="display:none;">Revlon</span>

我想提取 HTML 中的“Revlon”文本。我目前正在使用 html 请求并尝试获取选择器(CSS)和文本:

brandname = r.html.find('body > div:nth-child(96) > span:nth-child(2)', first=True).text.strip()

但这会返回None并出现错误。我不确定如何专门提取它。任何帮助,将不胜感激。

标签: pythonhtmlweb-scrapingpython-requests

解决方案


这是一个使用 Selenium 的工作解决方案:

from seleniumwire import webdriver
from webdriver_manager.chrome import ChromeDriverManager


driver = webdriver.Chrome(ChromeDriverManager().install())

website = 'https://www.boots.com/revlon-colorstay-makeup-for-normal-dry-skin-10212694'

driver.get(website)

brand_name = driver.find_element_by_xpath('//*[@id="estore_product_title"]/h1')

print('brand name: '+brand_name.text.split(' ')[0])

您也可以为此使用 beautifulsoup:

from bs4 import BeautifulSoup
import requests


urlpage = 'https://www.boots.com/revlon-colorstay-makeup-for-normal-dry-skin-10212694'

# query the website and return the html to the variable 'page'
page = requests.get(urlpage)
# parse the html using beautiful soup and store in variable 'soup'
soup = BeautifulSoup(page.content, 'html.parser')
name = soup.find(id='estore_product_title')
print(name.text.split(' ')[0])

推荐阅读