java从网页抓取数据(如何使用Java/Python访问网页和使用Python进行数据解析)
优采云 发布时间: 2021-09-21 18:14java从网页抓取数据(如何使用Java/Python访问网页和使用Python进行数据解析)
前言:
网络爬虫看起来仍然很神奇。然而,如果你想一想或者做一些研究,你就会知道爬行动物并没有那么先进。深刻的是,当我们有大量的数据时,即当我们的网络“图”中有越来越多的循环时,我们应该如何解决它
此物品文章仅用于吸引翡翠。本文主要介绍如何使用Java/Python访问web页面并获取web页面代码,Python模仿浏览器访问web页面,并使用Python分析数据。我希望我们能从这篇文章开始,一步一步地解决蜘蛛网神秘的一面
参考:
1.“编写自己的网络爬虫”
2.使用Python编写爬虫程序,爬升CSDN内容,完美解决403问题
运行效果图:
有很多内容。我只选择了一些来显示
作者环境:
系统:Windows7
CentOS6.5
操作环境:JDK1.7
Python2.6.6
IDE:EclipseRelease@k282.0
PyCharm4.5.1
数据库:mysqlver14.14 Distrib@k311.73
开发过程:1.使用java抓取页面
对于页面捕获,我们使用java来实现它。当然,您可以使用其他语言来开发它。但是
以“博客公园”主页为例,展示了使用Java捕获网页的过程:
public class RetrivePageSimple {
private static HttpClient httpClient = new HttpClient();
// 设置代理服务器
static {
httpClient.getHostConfiguration().setProxy("58.220.2.132", 80);
}
public static boolean downloadPage(String path) throws HttpException,
IOException {
PostMethod postMethod = new PostMethod(path);
// 执行,返回状态码
int statusCode = httpClient.executeMethod(postMethod);
System.out.println(statusCode);
// 针对状态码进行处理 (简单起见,只处理返回值为200的状态码)
if (statusCode == HttpStatus.SC_OK) {
String a = postMethod.getResponseBodyAsString();
System.out.println(a);
return true;
}
return false;
}
public static void main(String[] args) {
try {
RetrivePageSimple.downloadPage("http://www.cnblogs.com/");
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果信息不会显示在这里,太多--
2.grab页面使用Python
您可能会问我,为什么要使用Java版本的页面捕获,而在这里要编写python?这是必要的。因为作者在开发这个演示之前没有考虑问题。当我们使用java将网页抓取到python时,网页字符串太长,无法作为参数传递。您可能认为保存文件是一个不错的选择。如果HTML文件太多怎么办?是的,我们必须放弃这种累人的练习
考虑到参数长度的限制,我们只在Java端给出页面地址,并使用python抓取网页
最简单的方法是,我们通常使用Python网页,如下所示:
import urllib2
result = urllib2.urlopen('http://blog.csdn.net/mobile/index.html')
html = result.read()
print html
然而,作者的代码中使用了CSDN博客频道的URL。CSDN过滤爬虫的访问。我们将收到以下错误消息:
我被拒绝了
3.使用模拟浏览器登录网站
如前所述,当我们访问受保护的网页时,我们将被拒绝。但是,我们可以尝试使用自己的浏览器来访问它
换句话说,如果我们可以模仿Python中的浏览器,我们就可以访问这个网页。下面是Python模仿浏览器的代码:
import random
import socket
import urllib2
import cookielib
ERROR = {
'0':'Can not open the url,checck you net',
'1':'Creat download dir error',
'2':'The image links is empty',
'3':'Download faild',
'4':'Build soup error,the html is empty',
'5':'Can not save the image to your disk',
}
class BrowserBase(object):
def __init__(self):
socket.setdefaulttimeout(20)
self._content = None
def speak(self, name, content):
print '[%s]%s' % (name, content)
def open_url(self, url):
"""
打开网页
"""
cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
self.opener = urllib2.build_opener(cookie_support,urllib2.HTTPHandler)
urllib2.install_opener(self.opener)
user_agents = [
'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
'Opera/9.25 (Windows NT 5.1; U; en)',
'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7",
"Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 ",
]
agent = random.choice(user_agents)
self.opener.addheaders = [("User-agent", agent), ("Accept", "*/*"), ('Referer', 'http://www.google.com')]
try:
res = self.opener.open(url)
self._content = res.read()
# print self._content
except Exception, e:
self.speak(str(e)+url)
raise Exception
else:
return res
def get_html_content(self):
return self._content
def get_html_response(html):
spider = BrowserBase()
spider.open_url(html)
return spider.get_html_content()
上述代码通常可以获取返回值。让我们看一下返回结果
的解析过程。
4.数据分析
使用Python解析html非常简单:
import HTMLParser
class ListWebParser(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.tagDIVFlag = False
self.tagDIVAFlag = False
self.tagH1Flag = False
self.tagSecondHrefFlag = False
self._name = None
self._address = None
def handle_starttag(self, tag, attrs):
if tag == 'div':
for name, value in attrs:
if name == 'class' and value == 'blog_list':
self.tagDIVFlag = True
if tag == 'h1':
if self.tagDIVFlag:
self.tagH1Flag = True
# print 'h1->', self.tagH1Flag
if tag == 'a':
#if self.tagDIVAFlag:
#print 'h1: ', self.tagH1Flag
if self.tagH1Flag:
for name, value in attrs:
if name == 'target' and value == '_blank':
self.tagDIVAFlag = True
if name == 'href':
if self.tagSecondHrefFlag:
print '网址:', value
self._address = value
self.tagSecondHrefFlag = True
# if name == 'href' and self.tagDIVAFlag:
# print '网址:', value
# self._address = value
def handle_endtag(self, tag):
if tag == 'div':
self.tagDIVFlag = False
if tag == 'h1':
self.tagH1Flag = False
# print 'false h1.'
if tag == 'a':
self.tagDIVAFlag = False
def handle_data(self, data):
if self.tagDIVAFlag:
print u"名称:", data.decode("utf-8")
如果你说你在互联网上找到的HTML文件没有这个问题。我承认这一点,因为在正常情况下,解析一些简单的数据对我们来说非常容易。上面代码中的复杂逻辑处理过滤
说到筛选,我在这里使用了一个小技巧(当然,当更多的人使用它时,它不再只是一个技巧,但这种方法可以在未来的编码过程中作为参考)。我们通过标记的一些特殊属性(如ID、class等)锁定块。当我们启动块时,相应的标志位将被标记为true。当我们退出块时,相应的标志位将被标记为false。也许你觉得太麻烦了。事实上,如果你仔细想想,你就会知道这是有道理的
注意事项:
1.当使用java抓取页面时,我们使用代理服务器。此代理服务器的主机和端口可以直接在Internet上免费找到
2.您需要准备以下jar包并将其导入eclipse项目:
3.将Mysql的默认代码修改为UTF-8
这里会有一些中文信息,所以我们需要转换MySQL的编码格式
如果您是在Linux下编码,可以参考: