使用Python工具抓取网页
来源:互联网 发布:西西网络图绘制软件 编辑:程序博客网 时间:2024/09/21 09:29
最近在做一个基于文本分析的项目,需要抓取相关网页进行分析。我使用了Python的request和beautifulsoup组件包抓取和解析网页。在抓取过程中发现了很多问题,这些问题是在抓取工作开始之前,不曾预料到的。比如,由于不同网页的解析过程可能不一致,这可能导致解析失败;再比如,由于访问服务器资源过于频繁,可能会导致connection closed by remote host错误的出现。如下的代码考虑到了这两个问题。
import requestsimport bs4import time# output file nameoutput = open("C:\\result.csv", 'w', encoding="utf-8")# start requestrequest_link = "http://where-you-want-to-crawl-from"response = requests.get(request_link)# parse the htmlsoup = bs4.BeautifulSoup(response.text,"html.parser")# try to get the link starting with hreftry:link = str((soup.find_all('a')[30]).get('href'))except Exception as e_msg:link = 'NULL'# find the related appif (link.startswith("/somewords")):# sleeptime.sleep(2)# request the sub linkresponse = requests.get("some_websites" + link)soup = bs4.BeautifulSoup(response.text,"html.parser")# get the info you want: div label and class is o-content info_you_want = str(soup.find("div", {"class": "o-content"}))try:sub_link = ((str(soup.find("div", {"class": "crumb clearfix"}))).split('</a>')[2]).split('</div>')[0].strip()except Exception as e_msg:sub_link = "NULL_because_exception"try:info_you_want = (info_you_want.split('"o-content">')[1]).split('</div>')[0].strip()except Exception as e_msg:info_you_want = "NULL_because_exception"info_you_want = info_you_want.replace('\n', '')info_you_want = info_you_want.replace('\r', '')# write results into fileoutput.writelines(info_you_want + "\n" + "\n")# not find the aimed linkelse:output.writelines(str(e) + "," + app_name[e] + "\n")output.close()
0 0
- 使用Python工具抓取网页
- 使用python抓取网页
- 使用Python抓取网页信息
- python使用urllib2抓取网页
- 使用Python抓取网页信息
- 使用 Python 轻松抓取网页
- Python网页抓取工具Beautiful Soup面面观!
- 使用wget工具抓取网页和图片
- Python使用requests来抓取网页
- 使用python抓取网页上的信息
- Python使用代理抓取网页内容
- python使用ip代理抓取网页
- Python爬虫使用代理proxy抓取网页
- 网页抓取工具
- 网页数据包抓取工具
- Python抓取中文网页
- python抓取网页图片
- Python抓取中文网页
- Genymotion模拟器不能上网的解决办法
- 【LeetCode】Valid Parentheses
- cf 7a Kalevitch and Chess
- Mac系统显示和隐藏文件夹
- Positional parameter does not exist: 1 in query: from Books where isbn=?
- 使用Python工具抓取网页
- HDU1045
- KMP字符串模式匹配详解
- 树的父指针表示法(并查算法 重量权衡合并规则 路径压缩)
- 逆序与回文
- C语言第二章:运算符
- Perl中use strict
- 安卓canvas实现拖动显示大背景图片
- 浏览器插件之ActiveX开发