python - Beautifulsoup:解析html——获取href的一部分

标签 python web-scraping beautifulsoup request

我正在尝试解析

<td height="16" class="listtable_1"><a href="http://steamcommunity.com/profiles/76561198134729239" target="_blank">76561198134729239</a></td>

对于 76561198134729239。我不知道该怎么做。我尝试了什么:

import requests
from lxml import html
from bs4 import BeautifulSoup
r = requests.get("http://ppm.rep.tf/index.php?p=banlist&page=154")
content = r.content
soup = BeautifulSoup(content, "html.parser")
element = soup.find("td", 
{
    "class":"listtable_1",
    "target":"_blank"
})
print(element.text)

最佳答案

该 HTML 中有许多这样的条目。要获得所有这些,您可以使用以下方法:

import requests
from lxml import html
from bs4 import BeautifulSoup

r = requests.get("http://ppm.rep.tf/index.php?p=banlist&page=154")
soup = BeautifulSoup(r.content, "html.parser")

for td in soup.findAll("td", class_="listtable_1"):
    for a in td.findAll("a", href=True, target="_blank"):
        print(a.text)

这将返回:

76561198143466239
76561198094114508
76561198053422590
76561198066478249
76561198107353289
76561198043513442
76561198128253254
76561198134729239
76561198003749039
76561198091968935
76561198071376804
76561198068375438
76561198039625269
76561198135115106
76561198096243060
76561198067255227
76561198036439360
76561198026089333
76561198126749681
76561198008927797
76561198091421170
76561198122328638
76561198104586244
76561198056032796
76561198059683068
76561197995961306
76561198102013044

关于python - Beautifulsoup:解析html——获取href的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41720896/

相关文章:

python - Matplotlib:绘制一 strip 有开放标记的线,其中该线在标记内不可见

python - 在迭代到 .append() 元素期间创建新的列表名称

python - BeautifulSoup:从表单中抓取答案

javascript - 使用 Scrapy 获取 JavaScript 函数的参数

python - 如何获取beautifulsoup中所选标签的下一个标签(元素)

python - 美丽汤不会返回结果

python - 从漂亮的汤创建 html 文件的问题

python - Flask WTF – 表单总是重定向到 root

python - PyTorch 等效于 index_add_ 而不是取最大值

python - Beautiful Soup 在 "&quot;"和 "&lt;"等特殊字符上崩溃