Sna*_*xib 70 python beautifulsoup
我如何使用BeautifulSoup搜索仅包含我搜索的属性的标签?
例如,我想找到所有<td valign="top">标签.
以下代码:
raw_card_data = soup.fetch('td', {'valign':re.compile('top')})
获取我想要的所有数据,但也获取<td>具有该属性的任何标记valign:top
我也试过了:
raw_card_data = soup.findAll(re.compile('<td valign="top">'))
这没有任何回报(可能是因为正则表达式不好)
我想知道在BeautifulSoup中是否有一种方法可以说"查找<td>唯一属性为valign:top"的标签
更新
例如,如果HTML文档包含以下<td>标记:
<td valign="top">.....</td><br />
<td width="580" valign="top">.......</td><br />
<td>.....</td><br />
Run Code Online (Sandbox Code Playgroud)
我只想要第一个<td>tag(<td width="580" valign="top">)返回
Loï*_* G. 85
你可以用这个:
soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})
Run Code Online (Sandbox Code Playgroud)
编辑:
要返回仅具有valign ="top"属性的标记,可以检查标记attrs属性的长度:
from BeautifulSoup import BeautifulSoup
html = '<td valign="top">.....</td>\
<td width="580" valign="top">.......</td>\
<td>.....</td>'
soup = BeautifulSoup(html)
results = soup.findAll("td", {"valign" : "top"})
for result in results :
if len(result.attrs) == 1 :
print result
Run Code Online (Sandbox Code Playgroud)
返回:
<td valign="top">.....</td>
Run Code Online (Sandbox Code Playgroud)
Yog*_*esh 42
您可以按照文档lambda中的findAll说明使用函数.因此,在您的情况下,仅使用以下内容搜索标记:tdvalign = "top"
td_tag_list = soup.findAll(
lambda tag:tag.name == "td" and
len(tag.attrs) == 1 and
tag["valign"] == "top")
Run Code Online (Sandbox Code Playgroud)
Amr*_*Amr 21
如果您只想使用任何值搜索属性名称
from bs4 import BeautifulSoup
import re
soup= BeautifulSoup(html.text,'lxml')
results = soup.findAll("td", {"valign" : re.compile(r".*")})
Run Code Online (Sandbox Code Playgroud)
根据Steve Lorimer的说法,最好通过True而不是正则表达式
results = soup.findAll("td", {"valign" : True})
Run Code Online (Sandbox Code Playgroud)
Chr*_*ord 10
最简单的方法是使用新的CSS样式select方法:
soup = BeautifulSoup(html)
results = soup.select('td[valign="top"]')
Run Code Online (Sandbox Code Playgroud)
小智 6
在任何标签中查找使用属性
<th class="team" data-sort="team">Team</th>
soup.find_all(attrs={"class": "team"})
<th data-sort="team">Team</th>
soup.find_all(attrs={"data-sort": "team"})
Run Code Online (Sandbox Code Playgroud)
只需将其作为以下参数传递findAll:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("""
... <html>
... <head><title>My Title!</title></head>
... <body><table>
... <tr><td>First!</td>
... <td valign="top">Second!</td></tr>
... </table></body><html>
... """)
>>>
>>> soup.findAll('td')
[<td>First!</td>, <td valign="top">Second!</td>]
>>>
>>> soup.findAll('td', valign='top')
[<td valign="top">Second!</td>]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88831 次 |
| 最近记录: |