1、源介绍
我们使用的是来自中国的清华大学pypi镜像https://pypi.tuna.tsinghua.edu.cn/simple
打开一看,就是一个简单的HTML页面,里面有无数个链接。链接就是模块名。
Requests
import requests
a = requests.get("https://pypi.tuna.tsinghua.edu.cn/simple").text
可以打印a试一下(在PyCharm打不全,就不截图了)
BeautifulSoup解析
import bs4
b = bs4.BeautifulSoup(a, "lxml")
s = b.find_all("a")
记得安装lxml模块与bs4模块!
写入文件与tqdm
import tqdm
with open("pypi.txt", "w") as f:
for i in tqdm.tqdm(range(len(s)), total=len(s), desc="进度"):
f.write(str(s[i].text )+ "\n")
总程序
import requests
import bs4
import tqdm
a = requests.get("https://pypi.tuna.tsinghua.edu.cn/simple").text
b = bs4.BeautifulSoup(a, "lxml")
s = b.find_all("a")
with open("pypi.txt", "w") as f:
for i in tqdm.tqdm(range(len(s)), total=len(s), desc="进度"):
f.write(str(s[i].text )+ "\n")
进度: 100%|██████████| 273143/273143 [00:00<00:00, 353842.41it/s]
PS:运行较慢,主要是因为bs4效率不高(即使使用了lxml这个C语言库!)·

本文介绍了如何使用Python的requests、BeautifulSoup和tqdm库从中国清华大学的pypi镜像抓取所有模块名,并将结果写入文件,特别提到了BeautifulSoup解析效率的问题。
2万+

被折叠的 条评论
为什么被折叠?



