【问题标题】:BeautifulSoup returns 'none'BeautifulSoup 返回“无”
【发布时间】:2019-07-21 05:53:22
【问题描述】:

我接受获取 h2-tag 文本,但它显示“无”。它存在。 我试图改变 page.content 'html.parser to lxml' 等等。还是不行。

from bs4 import BeautifulSoup
import requests

headers = {"User-agent":"Mozilla/5.0 (X11; Linux x86_64) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 
Safari/537.36"}
url = 'http://www.unitedstateszipcodes.org/54115'
page = requests.get(url,headers=headers).text
soup = BeautifulSoup(page, 'html.parser')
div = soup.find('div', class_='col-xs-12').h2
print(div)

我试图在 xml 中更改页面内容,之后它显示elif len(markup) <= 256 and ( TypeError: object of type 'Response' has no len()

【问题讨论】:

  • 您能更好地解释一下您要做什么吗? .h2 是干什么用的?

标签: python html beautifulsoup


【解决方案1】:

要在&lt;div&gt;inside 中找到&lt;h2&gt; 元素,您可以在您找到的&lt;div&gt; 上使用另一个.find() 方法:

div = soup.find('div', class_='col-xs-12')
heading = div.find('h2')

【讨论】:

  • 太好了,为你高兴@RohitDalal :) 请接受解决了你的挑战的答案,这样有相同问题的其他人可以快速找到答案。
【解决方案2】:

您可以使用 select_one 并使用后代组合器来获取该父类的子 h2

soup.select_one('div.col-xs-12 h2').text

【讨论】:

  • 是的,它正在工作 C:\Users\ABC\Desktop&gt;python first_scraping_solve.py 输出 Search by ZIP, address, city, or county:
猜你喜欢
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 2020-11-03
  • 2020-08-02
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多