这里为了提防反爬,user_agent在多个里随机选,并使用了代理池(虽然不多),并且我电脑端也进行了局域网ip代理。
- # 定义第2个函数que_res,用来构建request发送请求,并返回响应response
- def que_res(url):
-
- # 构建request的第一步——构建头部:headers
- USER_AGENTS = [
- "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
- "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
- "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
- "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
- "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",
- "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)",
- "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
- "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)",
- "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)",
- "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
- ]
- user_agent = random.choice(USER_AGENTS)
- headers = {
- 'Accept-Language': 'zh-CN,zh;q=0.8',
- 'Connection': 'keep-alive',
- 'Host': 'www.某信托网.com',
- 'Referer': 'http://www.某信托网.com/Product/Index.aspx',
- 'User-Agent': user_agent,
- 'X-Requested-With': 'XMLHttpRequest'
- }
-
- # 构建request的第二步——构建request
- request = urllib.request.Request(url=url, headers=headers)
-
-
- # 发起请求的第一步——构建代理池
- proxy_list = [
- {'http':'125.40.29.100:8118'},
- {'http':'14.118.135.10:808'}
- ]
- proxy = random.choice(proxy_list)
-
- # 发起请求的第二步——创建handler和opener
- handler = urllib.request.ProxyHandler(proxy)
- opener = urllib.request.build_opener(handler)
-
- # 发起请求的第三步——发起请求,获取响应内容并解码
- response = opener.open(request).read().decode()
-
- # 返回值
- return response
④ 解析第一层网页的内容
获取响应之后就是解析并提取数据了,第一层使用正则表达式的方法来进行。 (编辑:核心网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|