基本信息
源码名称:python 爬取网址数据示例
源码大小:1.76KB
文件格式:.py
开发语言:Python
更新时间:2017-10-20
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 4 元×
微信扫码支付:4 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
#!/usr/bin/python # -*- coding: UTF-8 -*- from bs4 import BeautifulSoup import requests.exceptions from urllib.parse import urlsplit from collections import deque import re # 一个需要爬行的url队列 new_urls = deque(['https://www.baidu.com/']) # 一组我们已经爬过的url processed_urls = set() emails = set() # 一个一个地处理url,直到我们耗尽队列 while len(new_urls): # 将下一个url从队列移动到处理的url集合 url = new_urls.popleft() processed_urls.add(url) # 提取基本url以解析相对链接 parts = urlsplit(url) base_url = "{0.scheme}://{0.netloc}".format(parts) path = url[:url.rfind('/') 1] if '/' in parts.path else url # 获取url的内容 print("Processing %s" % url) try: response = requests.get(url) except (requests.exceptions.MissingSchema, requests.exceptions.ConnectionError): # 忽略页面错误 continue # 提取所有电子邮件地址并将它们添加到结果集 new_emails = set(re.findall(r"[a-z0-9\.\- _] @[a-z0-9\.\- _] \.[a-z] ", response.text, re.I)) emails.update(new_emails) # 为html文档创建一个beutiful汤 soup = BeautifulSoup(response.text) #查找并处理文档中的所有锚 for anchor in soup.find_all("a"): # 从锚中提取链接url link = anchor.attrs["href"] if "href" in anchor.attrs else '' # 解决相对链接 if link.startswith('/'): link = base_url link elif not link.startswith('http'): link = path link # 如果没有队列或处理,将新url添加到队列中 if not link in new_urls and not link in processed_urls: new_urls.append(link)