【问题标题】:Python BeautifulSoup soup.findPython BeautifulSoup 汤.find
【发布时间】:2018-03-14 16:48:47
【问题描述】:

我想使用 urllib 和 BeautifulSoup 从网站上抓取一些特定数据。 我试图获取文本“190.0 kg”。正如您在我的代码中看到的那样,我已经尝试过使用attrs={'class': 'col-md-7'} 但这会返回错误的结果。有没有办法指定我希望它返回<h3>之间的文本?

from urllib.request import urlopen
from bs4 import BeautifulSoup

# specify the url
quote_page = 'https://styrkeloft.no/live.styrkeloft.no/v2/?test-stevne'

# query the website and return the html to the variable 'page'    
page = urlopen(quote_page)

# parse the html using beautiful soup     
soup = BeautifulSoup(page, 'html.parser')

# take out the <div> of name and get its value    
Weight_box = soup.find('div', attrs={'class': 'col-md-7'})

name = name_box.text.strip() 
print (name)

【问题讨论】:

  • 你能提供实际的网址吗?
  • 返回错误结果是什么意思?你能发布你得到的输出吗?
  • 改为获取“可见流”。在html中搜索“Vis stream”,发现在col-md-7 visible-xs下。
  • 用真实网址更新了帖子。
  • @markusl2 检查页面来源。内容不可用,它是使用 Javascript 动态生成的。你不能简单地使用requests 模块来抓取它。看看Selenium

标签: python python-3.x beautifulsoup urllib


【解决方案1】:

由于此内容是动态生成的,因此无法使用requests 模块访问该数据。

您可以使用selenium webdriver 来完成此操作:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup

chrome_options = Options()
chrome_options.add_argument("--headless")

chrome_driver = "path_to_chromedriver"

driver = webdriver.Chrome(chrome_options=chrome_options,executable_path=chrome_driver)
driver.get('https://styrkeloft.no/live.styrkeloft.no/v2/?test-stevne')
html = driver.page_source
soup = BeautifulSoup(html, "lxml")
current_lifter = soup.find("div", {"id":"current_lifter"})
value = current_lifter.find_all("div", {'class':'row'})[2].find_all("h3")[0].text
driver.quit()

print(value)

请确保在您的机器中安装了 chromedriver 可执行文件。

【讨论】:

  • 工作就像一个魅力。谢谢!
  • 很高兴为您提供帮助。请考虑将答案标记为正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
  • 2020-11-18
  • 1970-01-01
  • 2020-05-03
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
相关资源
最近更新 更多