在Python中如何从字符串中剥离?

2024-10-04 09:27:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用BeautifulGroup将所有链接附加到数组“get_link”中。在

get_link = []
for a in soup.find_all('a', href=True):
    if a.get_text(strip=True):
     get_link .append(a['href'])

get_link的输出:

^{pr2}$

如何得到以下输出?在

^{3}$

Tags: textintrueforgetif链接link
2条回答

有很多方法只获取“country=”有些已经在bs4中,但是如果您愿意,可以使用regex:

import re
ui=['index.html?country=2',
 'index.html?country=25',
 'index.html?country=1',
 'index.html?country=6',
 'index.html?country=2']





pattern=r'(country=[0-9]{0,99})'



print("\n".join([re.search(pattern,i).group() for i in ui]))

结果:

^{pr2}$

获取具有非空文本值和href属性的所有a标记(链接)的优化方法:

links = [l.get('href').replace('index.html?','') 
         for l in soup.find_all('a', href=True, string=True) if l.text.strip()]
print(links)

相关问题 更多 >