Python爬蟲實現(免登陸站點)

**說明
此爬蟲應用場景:主要針對一些免登陸的網站實現的
一、示例
(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',οnclick="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
發佈了31 篇原創文章 · 獲贊 41 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章