【问题标题】:Extract value in Web scraping with Python Beautiful Soup使用 Python Beautiful Soup 在 Web 抓取中提取价值
【发布时间】:2021-02-23 14:55:53
【问题描述】:

如何从下面的 HTML 代码中提取值“1.00 TK = 779.8”?

我尝试了下面的代码,但它不起作用;

from bs4 import BeautifulSoup
page = requests.get(<url>).text

##here is the html page content'''<span _ngcontent-his-c101="" id="driveValue" class="ng-binding ng-scope"> 1.00 TK = 779.8<span _ngcontent-his-c101="">Disk Drive Value</span>(DDV) </span>'''

soup = BeautifulSoup(html, 'html.parser')
print(soup.find(id='driveValue').find_next(text=True).strip())

错误:

 AttributeError: 'NoneType' object has no attribute 'find_next'

【问题讨论】:

  • 我尝试使用 id="driveValue" 提取值,结果没有

标签: python html css web-scraping beautifulsoup


【解决方案1】:

使用find_next(),返回第一个匹配项:

from bs4 import BeautifulSoup

html = '''<span _ngcontent-his-c101="" id="driveValue" class="ng-binding ng-scope"> 1.00 TK = 779.8<span _ngcontent-his-c101="">Disk Drive Value</span>(DDV) </span>'''

soup = BeautifulSoup(html, 'html.parser')
print(soup.find(id='driveValue').find_next(text=True).strip())

输出:

1.00 TK = 779.8

编辑:使用Selenium

from bs4 import BeautifulSoup
from selenium import webdriver
from time import sleep

URL = "https://www.westernunion.com/us/en/web/send-money/start?SrcCode=12345&ReceiveCountry=IN&SendAmount=100&ISOCurrency=CNY&FundsOut=BA&FundsIn=CreditCard"

driver = webdriver.Chrome(r"C:\path\to\chromedriver.exe")
driver.get(URL)
sleep(10)

soup = BeautifulSoup(driver.page_source, "html.parser")

price = driver.find_element_by_css_selector("span.ng-binding.ng-scope").text
print(price)

driver.quit()

输出:

1.00 USD = 73.9375 Indian Rupee (INR)

【讨论】:

  • 出现错误 AttributeError: 'NoneType' object has no attribute 'find_next'
  • @itgeek 该页面可能是动态加载的。请参阅 my answer 使用 selenium 抓取动态页面。
  • 我也试过了, print(soup.find('span',id="driveValue")) 它打印“None”
  • 当我想从字符串 "html = ''' 1.00 TK = 779.8磁盘驱动器值(DDV) ''' "
  • 谢谢我知道使用硒的可能性。我想知道我是否可以不用硒。
【解决方案2】:

希望有帮助。

from lxml import etree
txt = '''<span _ngcontent-his-c101="" id="driveValue" class="ng-binding ng-scope"> 1.00 TK = 779.8<span _ngcontent-his-c101="">Disk Drive Value</span>(DDV) </span>'''

root = etree.fromstring(txt)
for td in root.xpath('//span[contains(@class, "ng-binding ng-scope")]'):
    print(td.text)

打印输出

1.00 TK = 779.8

【讨论】:

  • 谢谢 Samsul .. 有没有办法使用“ID”提取?
  • 当 OP 有 BeautifulSoup 标签时,为什么要使用 XML 解析?
  • 难道不能使用 beautifulSoap 吗?
  • 是的,可以使用 id 提取。我使用 XML 解析是因为易于使用的库,用于在 Python 中处理 XML 和 HTML。
  • 当我只使用字符串时它工作正常,但在这里我需要读取页面的内容,并提取值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2020-09-04
  • 1970-01-01
  • 2022-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多