【问题标题】:Unable to access table tag within BeautifulSoup--shows as declaration instead of tag无法访问 BeautifulSoup 中的表标签——显示为声明而不是标签
【发布时间】:2019-05-02 19:59:51
【问题描述】:

我正在使用 Jupyter Notebook 运行 Python3。我正在尝试在this page 上选择具有类属性“公司”的表行标签,但是在汤中的某个点之后无法选择任何标签。当我运行 findAll 时,它会产生一个空列表。包含该表的汤索引是 21,但是它显示为 bs4.element.Declaration 而不是标记,这可能是 findAll 什么都不返回的原因。

from bs4 import BeautifulSoup as bs  
import requests
url = 'http://theacsi.org/index.php?option=com_content&view=article&id=149&catid=&Itemid=214&i=Airlines'
r = requests.get(url, headers={
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'
        })
airlinesSatPage = r.content       
soup = bs(airlinesSatPage, "html.parser")
allRows = soup.findAll('tr',{'class':'Company'})
print(allRows)

任何想法发生了什么或我可以做些什么来访问这些标签?

【问题讨论】:

    标签: python python-3.x parsing beautifulsoup tags


    【解决方案1】:

    问题似乎是html.parser 无法处理从该 URL 返回的 HTML 标记。切换到lxml 解析器可以解决问题,但这需要单独的pip install lxml

    总之,首先:

    pip install lxml
    

    然后更改代码中的解析器:

    soup = bs(airlinesSatPage, "lxml")
    

    运行时,打印:

    [<tr class="Company"><td class="Company"> <a href="https://www.theacsi.org..., ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      相关资源
      最近更新 更多