首先附上代码:
#爬取瞬眼天下网页多页的小标题
import requests
from bs4 import BeautifulSoup
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
baseurl='http://www.tmtpost.com/nictation/'
urls=[]
filename='c:\\Users\\lws\Desktop\\shunyan.txt'#需要保存的位置
with open(filename,'w',encoding='utf-8') as f:
for page in range(1,10):
allurl=baseurl+str(page)
urls.append(allurl)
for url in urls:
resp=requests.get(url,headers=headers)
soup=BeautifulSoup(resp.text,'lxml')
alla=soup.find_all('h2',class_='w_tit')
for a in alla:
t=a.find('a')
f.writelines(t.get_text()+'\n')
print('success')
这里我是爬取的“瞬眼天下”网页新闻的小标题,并保存在了本地文本中