从BeautifulSoup中提取特定链接



我之前使用BeautifulSoup4提取了一些信息:https://www.peakbagger.com/list.aspx?lid=5651

我得到一个href:

的列表
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
url = 'https://www.peakbagger.com/list.aspx?lid=5651'
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
a= soup.select("a:nth-of-type(1)")
a

但是我只想要一个链接开始于'peak.aspx?pid=10…'

我如何只打印出'peak.aspx?pid=10…,我需要使用循环还是分割它?

谢谢。

一种方法可以是循环遍历您的选择,只选择包含字符串peak.aspx?pid =:

[x['href'] for x in soup.select('a') if 'peak.aspx?pid=' in str(x)]

但是您也可以指定您的selector来获得结果-这将只给您表中的第二列及其标记:

soup.select('table.gray  tr td:nth-of-type(2) a')

要获得链接,你必须循环结果:

[x['href'] for x in soup.select('table.gray  tr td:nth-of-type(2) a')]

最新更新