|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Python 爬取高匿 IP
网址:https://www.xicidaili.com/
需求:
爬取网页里的高匿IP和端口,
并保存进文件里。
用到的模块:
requests:把网页下载下来。
bs4: 解析利器,有了它,妈妈再也不用担心我不喜欢写正则了 !
爬取思路
先导入模块:
- from requests import get
- from bs4 import BeautifulSoup as BS
复制代码
OK,然后写打开URL的函数open_url():
- def open_url(url):
- # 写上 headers 好习惯
- headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36'}
- res = get(url)
- return res
复制代码
写道这一步就差不多了,开始分析网页。
翻一翻网页源代码,很容易发现所有
的IP和端口都在<td>标签里面:
太简单了!直接写出get_IP():
- def get_IP(res):
- soup = BS(res.text, "html.parser")
- target = soup.find_all("td") # 找出所有的td标签
- f = open("IP.txt", "w")
- for each in target:
- f.write(each.text) # 写入内容
- f.close()
复制代码
到了这一步就差不多了,直接写main吧:
- def main():
- url = 'https://www.xicidaili.com/'
- res = open_url(url)
- get_IP(res)
- if __name__ == "__main__":
- main()
复制代码
大功告成!可以看看文件啦! |
|