python - 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
并出现错误。我不确定如何专门提取它。任何帮助,将不胜感激。
解决方案
这是一个使用 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])
推荐阅读
- powershell - Powershell根据给定的计数选择一个随机字母并将每个字母动态分配给一个唯一的变量?
- c++ - CDT Eclipse 中调试配置的区别?
- asp.net - 如何解决“DataSet 不支持 System.Nullable<>.”?
- javascript - 使用其余端点 POST /users/{id}/verify 重新验证电子邮件
- mysql - 重复列名的循环 SELECT 语句
- python - 通过比较有效地更新字典列表
- docker - 为什么 docker ps 不显示我的 minikube 的 docker 容器?
- amazon-web-services - 谁能建议在线控制台练习大数据程序
- android - 在 Kotlin 主类中显示 onBindViewHolder 值
- python - 如何从数据框创建列表?