2016-11-14 64 views
0

我想所有的网站,其URL文本包括像productservicesolutionindex过滤器超链接 - 蟒蛇

字的超链接所以我想出了这个

site = 'https://www.similarweb.com' 
resp = requests.get(site) 
encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None 
soup = BeautifulSoup(resp.content, from_encoding=encoding) 

contact_links = [] 
for a in soup.find_all('a', href=True): 
    if 'product' in a['href'] or 'service' in a['href'] or 'solution' in a['href'] or 'about' in a['href'] or 'index' in a['href']: 
     contact_links.append(a['href']) 

contact_links2 = [] 
for i in contact_links: 
    string2 = i 
    if string2[:4] == 'http': 
     contact_links2.append(i) 
    else: 
     contact_links2.append(site+i) 

for i in contact_links2: 
    print i 

当运行https://www.similarweb.com这个片段它给出几个链接,其中一些是

https://www.similarweb.com/apps/top/google/app-index/us/all/top-free 
https://www.similarweb.com/corp/solution/travel/ 
https://www.similarweb.com/corp/about/ 
http://www.thedailybeast.com/articles/2016/10/17/drudge-limbaugh-fall-for-twitter-joke-about-postal-worker-destroying-trump-ballots.html 
https://www.similarweb.com/apps/top/google/app-index/us/all/top-free 

根据这一结果,我想只有那些链接,其中后这句话productservicesolutionindex不应该有任何更多的话

预期输出: (只考虑前5个链接)

https://www.similarweb.com/corp/about/ 

我该怎么办那?

+0

您想要删除哪个示例网址? – 2016-11-14 08:26:25

+0

那些,其中'产品''服务''解决方案''索引'应该在URL – Guru

+0

@LutzHorn下面的结尾字我想只在示例中的第三个网址 – Guru

回答

1

如果条件存在,你应该在检查单词前后加上反斜杠。它应该是if '/product/' in a['href'] ...等等。

正如评论中提到的那样,它应该是硬道理,那么最好检查一下a['href'].endswith('/product/')。 由于endswith函数可以将元组作为参数,所以你可以这样做:

if a['href'].endswith(('/product/', '/index/', '/about/', '/solution/', 'service'))

对于以元组中提到的任何字符串结尾的所有url,此条件将评估为true。

+0

我们是否也可以在这里包含正则表达式,以便可以覆盖变体。就像'about'' aboutus''关于我们'与endswith一起 – Guru

0
import requests 
from bs4 import BeautifulSoup 
import re 
from urllib.parse import urljoin 


r = requests.get('https://www.similarweb.com/') 
soup = BeautifulSoup(r.text, 'lxml') 
urls = set() 

for i in soup.find_all('a', href=re.compile(r'((about)|(product)|(service)|(solution)|(index))/$')): 
    url = i.get('href') 
    abs_url = urljoin(r.url, url) 
    urls.add(abs_url) 
print(urls)