【问题标题】:Python scraping returns nonePython 抓取返回无
【发布时间】:2020-01-06 15:20:27
【问题描述】:

我正在尝试使用 BeautifulSoup 从 HTML 页面中获取名称:

import urllib.request
from bs4 import BeautifulSoup

nightbot = 'https://nightbot.tv/t/tonyxzero/song_requests'
page = urllib.request.urlopen(nightbot)
soup = BeautifulSoup(page, 'html5lib')

list_item = soup.find('strong', attrs={'class': 'ng-binding'})
print (list_item)

但是当我打印print(list_item) 时,我得到一个none 作为回复。有办法解决吗?

【问题讨论】:

  • 试试 print(soup.prettify()) 看看你认为应该存在的标签是否真的存在。
  • 标签不存在。使用 Maaz 的解决方案有效。谢谢! :)

标签: python beautifulsoup scrapy


【解决方案1】:

网页由 javascript 呈现。所以你必须使用像selenium 这样的包来获得你想要的东西。

你可以试试这个:

代码:

import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('https://nightbot.tv/t/tonyxzero/song_requests')

html = driver.page_source

soup = BeautifulSoup(html, 'html.parser')

list_item = soup.find('strong', attrs={'class': 'ng-binding'})
print (list_item)

结果:

<strong class="ng-binding" ng-bind="$state.current.title">Song Requests: TONYXZERO</strong>

【讨论】:

  • 成功了!非常感谢!现在我唯一的问题是让他得到正确的 ng-binding
  • 如果你知道你的目标标签在哪里,你可以使用find_all() 方法而不是find(),它返回一个列表,然后在里面选择正确的标签。或者你必须找到另一种方式来选择它(另一个属性......)
猜你喜欢
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-27
相关资源
最近更新 更多