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