urllib基本用法

添加浏览器请求头下载网页并打印出网页html代码

from urllib import request
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') 
req = request.Request("http://www.baidu.com")

req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36")
resp = request.urlopen(req)
print(resp.read().decode('utf-8'))

POST请求

1.导入库 from urllib import parse

2.使用urlencode生成post数据

postData = parse.urlencode([
(key,val1),
(key,val2),
(key,valn)
])

3.使用postData发送post请求

urlopen(req, data=postData.encode(‘utf-8’))

4.得到请求状态
resp = urlopen(req, data=postData.encode(‘utf-8’))

测试响应数据:
Host:www.thsrc.com.tw
Origin:http://www.thsrc.com.tw
Referer:http://www.thsrc.com.tw/index.html?force=1
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36
Form Data
view source
view URL encoded

post数据:
StartStation:2f940836-cedc-41ef-8e28-c2336ac8fe68
EndStation:977abb69-413a-4ccf-a109-0272c24fd490
SearchDate:2017/02/12
SearchTime:10:30
SearchWay:DepartureInMandarin
RestTime:
EarlyOrLater:

爬虫代码

from urllib.request import urlopen
from urllib.request import Request
from urllib import parse

import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='gb18030') 

req = Request("http://www.thsrc.com.tw/tw/TimeTable/SearchResult")

postData = parse.urlencode([
    ("StartStation", "2f940836-cedc-41ef-8e28-c2336ac8fe68"),
    ("EndStation", "977abb69-413a-4ccf-a109-0272c24fd490"),
    ("SearchDate", "2017/02/12"),
    ("SearchTime", "10:30"),
    ("SearchWay", "DepartureInMandarin")

    ])
req.add_header("Origin", "http://www.thsrc.com.tw")

req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36")
resp = urlopen(req, data=postData.encode('utf-8'))
print(resp.read().decode('utf-8'))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python爬虫是指使用Python编写程序来自动化地从互联网上获取数据。爬虫通常通过HTTP或HTTPS协议发送请求,然后解析和提取返回的HTML或其他格式的数据。 urllib是Python标准库中用于处理URL的模块,提供了一系列函数和类来实现URL请求、解析、编码等功能。下面是urllib基本用法和高级用法的介绍: 基本用法: 1. 发送GET请求:使用urllib.request模块中的urlopen()函数发送GET请求,获取页面内容。 ```python from urllib.request import urlopen response = urlopen("http://example.com") content = response.read().decode("utf-8") print(content) ``` 2. 发送POST请求:使用urllib.request模块中的urlopen()函数发送POST请求,传递参数并获取页面内容。 ```python from urllib.request import urlopen, Request from urllib.parse import urlencode data = urlencode({"username": "john", "password": "secret"}).encode("utf-8") request = Request("http://example.com/login", data=data, method="POST") response = urlopen(request) content = response.read().decode("utf-8") print(content) ``` 3. 处理URL编码:使用urllib.parse模块中的urlencode()函数进行URL编码和解码。 ```python from urllib.parse import urlencode params = {"name": "John Doe", "age": 25} encoded_params = urlencode(params) print(encoded_params) # 输出: name=John+Doe&age=25 decoded_params = urlencode(encoded_params) print(decoded_params) # 输出: name=John Doe&age=25 ``` 高级用法: 1. 处理请求头:可以自定义请求头信息,包括User-Agent、Referer等。 ```python from urllib.request import urlopen, Request url = "http://example.com" headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"} request = Request(url, headers=headers) response = urlopen(request) content = response.read().decode("utf-8") print(content) ``` 2. 处理Cookie:可以通过CookieJar类来管理和使用Cookie,实现登录状态的维持。 ```python from urllib.request import urlopen, Request from http.cookiejar import CookieJar cookie_jar = CookieJar() opener = build_opener(HTTPCookieProcessor(cookie_jar)) install_opener(opener) request = Request("http://example.com") response = urlopen(request) content = response.read().decode("utf-8") print(content) # 获取Cookie cookies = cookie_jar._cookies print(cookies) ``` 3. 处理代理:可以通过ProxyHandler类设置代理服务器,并将其与urllib.request模块一起使用。 ```python from urllib.request import urlopen, Request, ProxyHandler, build_opener proxy_handler = ProxyHandler({"http": "http://proxy.example.com:8080"}) opener = build_opener(proxy_handler) request = Request("http://example.com") response = opener.open(request) content = response.read().decode("utf-8") print(content) ``` XPath是一种用于在XML和HTML文档中定位和提取数据的查询语言。在Python爬虫中,可以使用lxml库中的etree模块来解析HTML或XML文档,并使用XPath语法进行数据提取。下面是XPath的基本使用示例: ```python from lxml import etree html = """ <html> <body> <div id="content"> <h1>Page Title</h1> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </div> </body> </html> """ # 创建解析器 parser = etree.HTMLParser() tree = etree.fromstring(html, parser) # 使用XPath提取数据 title = tree.xpath("//h1/text()")[0] print(title) # 输出: "Page Title" items = tree.xpath("//ul/li/text()") print(items) # 输出: ["Item 1", "Item 2", "Item 3"] ``` XPath语法包括路径表达式、谓词、运算符等,可以根据元素的标签名、属性、层级关系等进行定位和筛选。通过使用XPath,可以方便快捷地从HTML或XML文档中提取所需的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值