【问题标题】:find_all with multiple attributes具有多个属性的 find_all
【发布时间】:2019-01-18 00:26:19
【问题描述】:

我想找到所有页面上的链接,这段代码只获取以http://开头的链接,但是大部分链接都是https://我该如何编辑你的代码在下面找到两者?

for link in soup.find_all('a',attrs={'href':re.compile("^http://")}):

import requests,bs4,re
res=requests.get('https://www.nytimes.com/2018/11/21/nyregion/president-trump-immigration-law-firms.html?action=click&module=Top%20Stories&pgtype=Homepage')
soup=bs4.BeautifulSoup(res.text,'html.parser')
x=[]
y=[]
z=[]
for link in soup.find_all('a',attrs={'href':re.compile("^http://")}):
    print(link.get('href'))
    x=link.get('href')

我知道我可以简单地获取所有链接,但我想同时获得 http://https:// find_all

for i in soup.select('a'):
    print(i.get('href'))

【问题讨论】:

  • 如何使用这个正则表达式 ^(http|https)://.* 。 ?
  • 或使用^http*://[a-zA-z]
  • 如果要查找所有链接,为什么要过滤属性?
  • @Barmar 链接带有它们的文本和字体格式以及类似的东西
  • @Enix 你的编辑作品,如果你愿意,你可以发布作为答案

标签: python python-3.x beautifulsoup findall


【解决方案1】:

你可以使用这个正则表达式来匹配http或者https

^(http|https)://.*

正则表达式(a|b)表示:匹配模式ab

【讨论】:

    【解决方案2】:

    您想将您的链接分类为 http 和 https 吗?使用.startswith()re.match() 找到它

    http = []
    https = []
    for link in soup.find_all('a'):
        url = link.get('href')
        if url.startswith('http://'): # or: if re.match("^http://", url)
          http.append(url)
        else:
          # should be https://
          https.append(url)
    
    print(https)
    print(http)
    

    【讨论】:

    • 这不会一直有效,我认为您应该使用 elif 而不是 else,以消除任何可能的错误,对吗?
    • 这只是一个示例,您可以通过添加 elif 来改进它。
    猜你喜欢
    • 2021-11-16
    • 1970-01-01
    • 2018-08-06
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 2018-07-17
    相关资源
    最近更新 更多