Python例子

检测含有某个关键字的页面url和链接

检测含有某个关键字的页面url和链接,直接上代码:

import requests
import re
import html
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36",
}
keyword = input('请输入关键字:')
# print(keyword)
with open('urls.txt','r',encoding='utf-8') as f:
    url_list = f.readlines()
new_urllist = []
for url_str in list(set(url_list)):
    if 'http' not in url_str:
        url_str = 'http://'+ url_str
    url = url_str.replace('\n','')
    if len(url) > 10:
        new_urllist.append(url)
# print(new_urllist)
for url in new_urllist:
    try:
        content = requests.get(url,headers=headers,timeout=3).text
        if ('å' or 'Ê') in content:
            content = requests.get(url, headers=headers, timeout=3).text.encode('raw_unicode_escape').decode()
        if keyword in content:
            title = re.compile(r'<title>(.*?)</title>', re.I).findall(content)[0]
            if '&#' in title:
                title = html.unescape(title)
            url_title = url + '\t\t\t' + title + '\n'
            with open('new_urls.txt','a',encoding='utf-8') as f:
                f.write(url_title)
        else:
            title = '网页没有关键字'
    except Exception as e:
        title = '链接打不开'
    print('{} ===》{}'.format(url,title))


最后修改:2021-08-03 14:39:32