可以先来看到 https://www.ptt.cc/ask/over18 的验证页面:
按下我同意后就会跳转至主页,可以看到表单是以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()範例,参数:
接下来我们要开始用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') #这边空一行才不会跟下面连一起
运行的结果: