如果我使用以下功能,我可以从网站上获取我需要的文本和链接:
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/