学习爬虫的简单代码,日后努力提高水平
通过这个小代码理解一下爬虫的基本原理
code:
from urllib import request
from bs4 import BeautifulSoup
url = "http://forge.educoder.net/competitions/"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
page = request.Request(url, headers=headers)
page_info = request.urlopen(page).read().decode('utf-8')
soup = BeautifulSoup(page_info, 'html.parser') #解析html
titles = soup.find_all('a', 'competition-Img') #找标签为a,且class为competition-Img
with open(r"./ans.txt", "w") as file:
for title in titles:
file.write("http://forge.educoder.net/competitions/" + title.get('href') + '\n\n')
利用简单的a标签class匹配规则进行爬虫