python抓頁面基礎知識
python抓頁面基礎知識
1.定義函數根據url獲得頁面
def getPageContent(self,url):
request = urllib2.Request(url)
response = urllib2.urlopen(request)
return response.read().decode('UTF-8')
2. 正則表達式匹配,re.S是dotall模式,意思是.表示所有字符的意思包括換行,()是分組的意思
pattern = re.compile('<div class="d_author">.*?<ul class="p_author">.*?'+
'<li class="d_name".*?<a.*?'+
'target="_blank">(.*?)</a>',re.S)
content = re.findall(pattern, pagecontent)
3.第二步中的content是數組,通過循環將數據寫到文件,item是tuple類型使用[]使用,item[0]爲第一列數據,item[1]爲第二列,以此類推。
f = open('1.txt','a+')
for item in content:
f.writelines((str(item[0])+str(item[1])+item[2].encode('UTF-8'),f)
1.定義函數根據url獲得頁面
def getPageContent(self,url):
request = urllib2.Request(url)
response = urllib2.urlopen(request)
return response.read().decode('UTF-8')
2. 正則表達式匹配,re.S是dotall模式,意思是.表示所有字符的意思包括換行,()是分組的意思
pattern = re.compile('<div class="d_author">.*?<ul class="p_author">.*?'+
'<li class="d_name".*?<a.*?'+
'target="_blank">(.*?)</a>',re.S)
content = re.findall(pattern, pagecontent)
3.第二步中的content是數組,通過循環將數據寫到文件,item是tuple類型使用[]使用,item[0]爲第一列數據,item[1]爲第二列,以此類推。
f = open('1.txt','a+')
for item in content:
f.writelines((str(item[0])+str(item[1])+item[2].encode('UTF-8'),f)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.