练习2:用Session和cookie以get方式通过18岁同意条款页面

可以先来看到 https://www.ptt.cc/ask/over18 的验证页面:

http://img2.58codes.com/2024/20114309BSpMX8saO4.png

按下我同意后就会跳转至主页,可以看到表单是以POST的形式传送,确认预设的值是'yes',所以接下来我们要带着建立的session,以POST的方式带着参数登入,再用cookie以GET的方式带着餐数进入主页。
因为requests.post()附带了payload和自订headers参数,所以我们先建立他们。P.S.这边表头(headers)的user-agent我是用google-bot的 详细网址。

#最好加入于import模块下方payload = {    'from': 'https://www.ptt.cc/bbs/Gossiping/index.html',    'yes': 'yes'}headers = {    'user-agent': 'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Safari/537.36'}#下面其实可以先省略,因为等等要用requests.Sessions()储存cookierequests.post('https://www.ptt.cc/ask/over18', data = payload, headers = my_headers) 

requests.post()範例,参数:
http://img2.58codes.com/2024/20114309XHYbVItQR5.png
接下来我们要开始用requests.Sessions()去产生、储存cookie,先建立sessions物件'rs'以post方式去请求,最后以get方式用相同的cookie向目标页面提出请求,并将传回的结果储存在res中。

    #这边依旧是在for迴圈里~    rs = requests.Session()    rs.post('https://www.ptt.cc/ask/over18', data = payload,headers = my_headers)    res = rs.get(url = header_url, headers = my_headers)

最后再次将取得的资料用BeautifulSoup去进行解析整理。

    # 接下来解析get到的res资料    soup = BeautifulSoup(res.text, 'html.parser')    r_ent = soup.select('div.r-ent')[0].text    a_url = soup.select('div.title a')[0]['href']    a_title = soup.select('div.title')[0]    print('版被第一篇:', a_title.text)    a_author = soup.select('div.author')[0]    print('第一篇写者:',a_author.text)    a_date = soup.select('div.date')[0]    print('第一篇日期:',a_date.text)    print('第一篇网址:'+'https://www.ptt.cc'+ a_url)     print('\n') #这边空一行才不会跟下面连一起

运行的结果:
http://img2.58codes.com/2024/20114309ET2knMLJ2N.png


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章