-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathspider.py
36 lines (28 loc) · 894 Bytes
/
spider.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# coding=utf-8
import requests
from lxml import html
import os
class Spider():
def getHtml(self, url, retryNum=5):
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
try:
rsp = requests.get(url, headers=headers, timeout=20)
except Exception as e:
if retryNum > 0:
return self.getHtml(url, retryNum - 1)
if rsp.status_code == 200:
return rsp.content
else:
if retryNum > 0:
return self.getHtml(url, retryNum-1)
def extraInfo(self, htmlPage, xpath):
tree = html.fromstring(htmlPage)
lists = tree.xpath(xpath)
if len(lists) == 1:
return lists[0]
return lists
if __name__ == '__main__':
spider = Spider()
rsp = spider.getHtml('http://www.yocajr.com/news/16492/')
c = spider.extraInfo(rsp,'/html/body/div[4]/div[1]/div[2]/text()')
print ''.join(c)