今天练习了抓取多页天涯帖子,重点复习的知识包括
这里有一个疑问:有时候一个标签可以有多个属性,不知道soup.find_all()能不能接受不止一个属性以缩小查找的范围。
# 引入库和请求头文件 import requests from bs4 import BeautifulSoup headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36' } # 定义主体函数。函数主体由四部分组成: #1.请求网址 #2.解析网页,形成可查找的html格式 #3.通过soup.select或者sopu.find_all查找需要的标签 #4.通过zip()代码将多个内容合并在一起 def get_content(url): res = requests.get(url,headers = headers) res.encoding = 'utf-8' soup = BeautifulSoup(res.text,'html.parser') contents = soup.find_all('div','bbs-content') authors = soup.find_all('a','js-vip-check') for author,content in zip(authors,contents): data = { 'author':author.get_text().strip(), 'content': content.get_text().strip() } print(data) # 在这里构造一个两层链接结构:帖子的1、2、3、4页和帖子的详情页的关系在这里实现 if __name__ == '__main__': urls = ['http://bbs.tianya.cn/post-develop-2271894-{}.shtml'.format(str(i)) for i in range (1,5)] # 要注意,这里的‘5'是不包括在范围里的 for url in urls: get_content(url)
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。