Day06—homework

本文介绍了一个使用Python的requests和re模块进行网页爬取的实例,目标是从搜索结果中提取有效的网址,并进一步从这些网址中抓取电子邮箱地址。通过正则表达式匹配,实现了对http链接及邮箱地址的有效识别。

Day06—homework


纸上得来终觉浅,绝知此事要躬行
眼泪你别问,joker这个 “男人” 你别恨。


爬取邮箱

编写程序:

import requests
import re

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
}
#网页源代码
url = 'https://www.baidu.com/s?wd=%E7%95%99%E4%B8%8B%E9%82%AE%E7%AE%B1'
response = requests.get(url,headers=headers)
html = response.text
str_ = html
#利用正则表达式,爬取所有http,爬成一个列表  
regex = re.compile('.*?\"(http.*?//.*?)\".*?')
res = regex.findall(str_)
#将能用的网址放到列表ress中
ress = []
for i in res:
    if 'cache.baiducontent' not in i:
        res.remove(i)
        ress.append(i)
del ress[0]

#利用子进程爬出邮箱并插入
for http in ress: 
    response1 = requests.get(http,headers=headers)
    html1 = response1.text
    regex1 = re.compile("[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?")
    res1 = regex1.findall(html1)
    xxx = str(res1)
    with open('‪email.txt',mode='w') as f:
        f.write(xxx)

改进:

import requests
import re

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
}
#网页源代码
url = 'https://www.baidu.com/s?wd=%E7%95%99%E4%B8%8B%E9%82%AE%E7%AE%B1'
response = requests.get(url,headers=headers)
html = response.text
#利用正则表达式,爬取所有http,爬成一个列表  
regex = re.compile("[a-zA-z]+://[^\s]*")
res = regex.findall(html)
#将能用的网址放到列表ress中
ress = []
for i in res:
    if 'cache.baiducontent.com/c?m=9'  in i:
        ress.append(i)
del ress[0]

#遍历并进入所有url,得到网页源代码,用正则表达式爬出邮箱并插入
for http in ress: 
    response1 = requests.get(http,headers=headers)
    html1 = response1.text
    regex1 = re.compile("[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?")
    res1 = regex1.findall(html1)
    #写入
    for r in res1:
        print(r)
        with open('‪email.txt',mode='w') as f:
            for i in res1:
                xxx = i.encode('UTF-8')
                f.write(xxx+'\n')
                f.close
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值