【发布时间】:2015-05-04 08:57:59
【问题描述】:
我对 Python 完全陌生,只是尝试我的编码技能来开发一些程序
我在 Python 2.7 中编写了以下程序以从目录中获取配置文件 URL - http://www.uschirodirectory.com/entire-directory/list/alpha/a.html
但是,我注意到获取的 URL 列表中有很多重复的条目。有人可以查看代码并告诉我是否有我正在做的事情,或者是否有办法进一步优化此代码。
非常感谢
import requests
from bs4 import BeautifulSoup
def web_crawler(max_pages):
p = '?site='
page = 1
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
while page <= max_pages:
for i in alpha:
url = 'http://www.uschirodirectory.com/entire-directory/list/alpha/' + str(i) + '.html' + p + str(page)
code = requests.get(url)
text = code.text
soup = BeautifulSoup(text)
for link in soup.findAll('a',{'class':'btn'}):
href = 'http://www.uschirodirectory.com' + link.get('href')
print(href)
page += 1
i += alpha[0 + 1]
#Run the crawler
web_crawler
【问题讨论】:
标签: python-2.7 for-loop while-loop web-scraping beautifulsoup