-
Notifications
You must be signed in to change notification settings - Fork 0
/
requests_xpath.py
49 lines (37 loc) · 1.19 KB
/
requests_xpath.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
37
38
39
40
41
42
43
44
45
46
47
48
49
"""
基于requests库作用实现网络请求
基于xpath实现数据提取
"""
import requests
from lxml import etree
class RequestError(Exception):
"""
请求异常
"""
pass
class ParseError(Exception):
"""
解析异常
"""
pass
def get(url):
resp = requests.get(url,
headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'},
proxies={'http': 'http://49.77.208.198:9999'})
if resp.status_code == 200:
parse(resp.text)
else:
raise RequestError('请求失败!')
def parse(html):
# 使用xpath解析
root = etree.HTML(html) # Element元素对象
divs = root.xpath('//div[@class="li-itemmod"]') # List[<Element>, <Element>,...]
#print(divs)
for div in divs:
# cover_url = div.xpath('.//img/@src') # list['', ]
# 提取src的属性值
cover_url = div.xpath('.//img/@src')[0] # list['', ]
title = div.xpath('.//h3/a/text()')[0]
print(cover_url, title)
if __name__ == '__main__':
get('https://chengdu.anjuke.com/community/?from=esf_list_navigation')