python - 需要正则表达式或者 BeautifulSoup 可以优化输出

标签 python

如果我使用以下功能,我可以从网站上获取我需要的文本和链接:

def get_url_text(url):
    source = requests.get(url)
    plain_text = source.text
    soup = BeautifulSoup(plain_text)
    for item_name in soup.findAll('li', {'class': 'ptb2'}):
        print(item_name.string)
        print (item_name.a)

get_url_text('https://www.residentadvisor.net/podcast.aspx')

返回:

RA.532 Marquis Hawkes
<a href="/podcast-episode.aspx?id=532"><h1>RA.532 Marquis Hawkes</h1></a>
RA.531 Evan Baggs
<a href="/podcast-episode.aspx?id=531"><h1>RA.531 Evan Baggs</h1></a>
RA.530 MCDE vs Jeremy Underground

如果我只想要 href 链接而不是它周围的标签等,我需要使用正则表达式还是 BeautifulSoup 中是否有其他方法?

期望的输出是:

RA.532 Marquis Hawkes
https://www.residentadvisor.net/podcast-episode.aspx?id=532

对于每个相似的元素。

最佳答案

您可以使用 print(item_name.a['href']) 并(如果需要)在前缀 https://www.residentadvisor.net 前添加(因为网页中的链接以没有明确方案和 netloc 部分的形式使用 - 例如,/podcast-episode.aspx?id=528)

关于python - 需要正则表达式或者 BeautifulSoup 可以优化输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39378971/

相关文章:

带循环的 Python doctest

python - Apache 上的 Django 网站,wsgi 失败

java - 无法在 Nest Rest API 上设置温度

python - 在 Python 中解码双重编码的 utf8

python - 您可以在 Python 类型注释中指定方差吗?

python - python 中的对象属性

python - MVP:Presenter-Model 通信

python - 如何与 Django 一起设置连续运行的进程?

python - 在 Networkx 1.10 中,configuration_model() 获得了关键字参数 'create_using' 的多个值

Python 谷歌文档字符串格式 : more than one type for argument?