【问题标题】:How to strip from string in Python?如何从Python中的字符串中剥离?
【发布时间】:2018-03-16 19:32:53
【问题描述】:

我正在使用 beautifulsoup 将所有链接附加到数组“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 的输出:

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

如何得到下面的输出?

[country=2',
 country=25',
 country=1',
 country=6',
 country=2']

【问题讨论】:

  • 我不明白你在问什么。您的标题与您显示的代码几乎没有关系。您是否只是想弄清楚如何获取每个 index.html?country=... 字符串的 country=... 部分?使用str.index 和切片似乎很容易,但是我会写一个答案,说当我完全不确定这实际上是您要问的问题时。
  • @Blckknght 我的英语不好,所以我无法更好地解释。有什么方法可以将右、左函数与数组一起使用,这样我就可以只保留数组 get_link 的必要文本
  • 对不起,我还是不明白你所说的“左右函数”是什么意思。如果您的所有链接都是同一种类型(它们总是以index.html? 开头,而这正是您想要截断的内容,那么您可以执行get_link.append(a['href'][11:])[11:] 是截断前 11 个字符的切片。如果您的链接看起来不同,您可能需要更复杂的逻辑。
  • get_link.append(a['href'][11:]) 它已经工作了。感谢您的宝贵时间。

标签: python python-3.x pandas beautifulsoup


【解决方案1】:

获取所有具有非空文本值和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)

【讨论】:

  • 是的,这是删除“index.html”的另一种方法?谢谢!
【解决方案2】:

有很多方法可以只获取“country=”,有些已经在 bs4 中,但如果你愿意,可以使用正则表达式:

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]))

结果:

country=2
country=25
country=1
country=6
country=2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 2010-09-19
    • 2012-09-30
    • 2018-04-20
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多