【问题标题】:Python web scraping, using html-requests to find a specific element and extract textPython 网页抓取,使用 html-requests 查找特定元素并提取文本
【发布时间】:2021-04-15 12:54:36
【问题描述】:

我正在使用 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 和一个错误。我不确定如何专门提取它。任何帮助将不胜感激。

【问题讨论】:

标签: python html web-scraping python-requests


【解决方案1】:

这是一个使用 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])

【讨论】:

    【解决方案2】:

    试试这个方法 .find("span", itemprop="品牌") 我认为这是工作

    from bs4 import BeautifulSoup
    import requests
    
    
    urlpage = 'https://www.boots.com/revlon-colorstay-makeup-for-normal-dry-skin-10212694'
    
    page = requests.get(urlpage)
    # parse the html using beautiful soup and store in variable 'soup'
    soup = BeautifulSoup(page.content, 'html.parser')
    print(soup.find("span", itemprop="Brand").text)
    

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 2022-01-19
      • 2019-02-03
      相关资源
      最近更新 更多