【问题标题】:Python,BeautifulSoup4: select elements where multiple attributes equal multiple values respectivelyPython,BeautifulSoup4:选择多个属性分别等于多个值的元素
【发布时间】:2017-12-18 01:26:58
【问题描述】:
<TABLE cellSpacing=0 cellPadding=0 width=700 border=0 617px; HEIGHT: 22px 23px 536px;>
    ...
</TABLE>

我想像上面一样选择所有元素:标签是TABLE,并且有几个属性(cellSpacing=0,cellPadding=0,width=700,border=0)。

我尝试了以下 python 脚本:

import requests
from bs4 import BeautifulSoup
result=requests.get("http://news.scu.edu.cn/news2012/cdzx/I0201index_1.htm")
result.encoding="GBK"
soup=BeautifulSoup(result.text,"html.parser")
soup=soup.find("TABLE",attrs={"cellspacing":"0","cellpadding": "0","width": 
"700","border":"0"})
print(soup)

脚本运行没有错误,但是漂亮的汤什么也没找到。这一定是错误的,如果你用Chrome打开页面(http://news.scu.edu.cn/news2012/cdzx/I0201index_1.htm),右键单击,进入inspect->Network->Doc->Response,搜索&lt;TABLE cellSpacing=0 cellPadding=0 width=700 border=0 617px; HEIGHT: 22px 23px 536px;&gt;,你会找到30个匹配的结果。

【问题讨论】:

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


    【解决方案1】:

    TABLE 标签名称必须小写:

    soup = soup.find("table", ...)
    

    这是reference section in the documentation

    由于 HTML 标记和属性不区分大小写,所有三个 HTML 解析器将标记和属性名称转换为小写。即标记&lt;TAG&gt;&lt;/TAG&gt; 转换为&lt;tag&gt;&lt;/tag&gt;

    【讨论】:

    • 谢谢,伙计!没错,我将“TABLE”改为“table”,最后美汤返回了一些有效信息。但似乎还有另一个问题:美汤只返回30的第一个元素,你知道是什么问题吗?
    • @bowen 你试过find_all()而不是find()吗?
    • 哎呀,对不起,我可以用谷歌搜索它。对不起,我一定是浪费了你的时间。非常感谢!!!
    猜你喜欢
    • 2014-07-10
    • 2019-10-20
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    相关资源
    最近更新 更多