python访问网页(python访问网页获取元素)

http://www.itjxue.com  2023-03-27 19:54  来源:未知  点击次数: 

如何用python访问网页并在表单处输入内容

我用过selenium模拟浏览器

使用selenium的chrome或firefox的webdriver打开浏览器

driver.get(url) #访问你的网页from=driver.find_elements_by_xpath("xxx")通过xpath或id等方法锁定到网页上表单的那个元素后,用

from.send_keys("xxx")来输入内容

python3.6怎么访问网页

使用Python访问网页主要有三种方式: urllib, urllib2, httplib

urllib比较简单,功能相对也比较弱,httplib简单强大,但好像不支持session

1. 最简单的页面访问

res=urllib2.urlopen(url)

print res.read()

2. 加上要get或post的数据

data={"name":"hank", "passwd":"hjz"}

urllib2.urlopen(url, urllib.urlencode(data))

3. 加上http头

header={"User-Agent": "Mozilla-Firefox5.0"}

urllib2.urlopen(url, urllib.urlencode(data), header)使用opener和handler

opener = urllib2.build_opener(handler)

urllib2.install_opener(opener)

4. 加上session

cj = cookielib.CookieJar()

cjhandler=urllib2.HTTPCookieProcessor(cj)

opener = urllib2.build_opener(cjhandler)

urllib2.install_opener(opener)

5. 加上Basic认证

password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

top_level_url = ""

password_mgr.add_password(None, top_level_url, username, password)

handler = urllib2.HTTPBasicAuthHandler(password_mgr)

opener = urllib2.build_opener(handler)

urllib2.install_opener(opener)

6. 使用代理

proxy_support = urllib2.ProxyHandler({"http":""})

opener = urllib2.build_opener(proxy_support)

urllib2.install_opener(opener)

7. 设置超时

socket.setdefaulttimeout(5)

python爬取网页内容数据需要打开网页吗

Python爬取网页内容需要打开网页,因为打开网页的时候才可以打开相对于的内容,因此需要爬取对应的数据需要进行内容的爬取网页的打开才可以

(责任编辑:IT教学网)

更多