您的位置:首页 > 编程语言 > Python开发

Python爬虫实现(免登陆站点)

2016-11-25 17:34 423 查看
**说明

此爬虫应用场景:主要针对一些免登陆的网站实现的

一、示例

(1)以下示例是爬取一个网站”多页”内容的结果,可以登陆其网站观察爬虫多页信息

(2)试验中经常出现返回结果是ResultSet(find/findAll)的问题,仿照此例

为模板可以提供一种解决方法

import re
import urllib2
import sys
from bs4 import BeautifulSoup
def multiSpider(k):
while k<9:
k = k + 1
url = "%s%d%s"%("http://bbs.haoyisheng.com/forum-231-",k,"html")
content = urllib2.urlopen(url).read()
bsObj = BeautifulSoup(content,"html5lib")
table = bsObj.find(id="threadlisttableid")
//注意此行如果存在多个table可以使用下面的循环进行,“切记循环”
th = table.findAll("th")
for a in th:
for col in a.find_all('a',onclick="atarget(this)"):
print(col.get_text())
multiSpider(5)


二、python对象数据类型问题如何解决

Python之变量类型错误一种简单有力的神奇调试之法。近来进行网络爬虫学习,目前只针对web页面,且没有登录和验证码验证信息的页面进行测试。这个过程中主要使用BeautifulSoup。

在进行处理的时候主要使用了find与findAll函数,以及正则匹配re模块的一些功能。这是过滤数据的一些常用内容,总之刚刚开始,狗屎般的百度,成了我的依靠,基本思路稳定之后,依然出现一些手足无措的问题,经过最后的分析,发现了一个问题,从一开始一直出现的一个问题就是,Python中复杂多变的变量类型导致各种的不爽。

所以根据经验确定操作对象的操作类型是否一致,否则进行操作时经常会报错,为此,为初学者提供了一种识别python类型的基础方法。 (1)首先导入types模块

(2)对当前错误关联的变量进行变量类型鉴定,确定操作类型无误

mport sys
import types
import urllib2
import re
from bs4 import BeautifulSoup
reload(sys)
sys.setdefaultencoding('gbk')
url1 = "http://zixun.haodf.com/index/1.htm"
data1 = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586',
'Accept': 'text / html, application / xhtml + xml, image / jxr, * / *',
'Accept - Encoding': 'gzip, deflate',
'Accept - Language': 'zh - CN',
'Connection': 'Keep - Alive',
'Host':'zixun.haodf.com',
}
req = urllib2.Request(url1,headers=data1)
content = urllib2.urlopen(req).read()
bsobj = BeautifulSoup(content,"html.parser")
html = bsobj.find("div",{"class":"izixun-department"})
ul = html.findAll("ul")
for i in ul:
fenlei1 = i.find("li",{"class":"izixun-department-title"}).get_text()
list1 = i.find("li",{"class":"izixun-department-list"})
for link1 in list1:
if link1.find("href=") == -1:
continue
else:
link = link1.get_text()
demo = str(link1)
rule = r'http\:\/\/[a-zA-Z0-9\.\/]+'
compile_rule = re.compile(rule)
href = compile_rule.findall(demo)
url2 = href[0]
hhh = "%s,%s,%s" % (fenlei1, link, url2)
task_raw = str(hhh).encode("utf-8")
#在怀疑类型不一致处使用type,查看其类型是否一致
print type(task_raw),task_raw
print type("sitemap")
if task_raw.find("sitemap") == -1:
print task_raw
else:
continue
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息