2016-06-28 25 views
1

divのデータを得るが、 をnullを返しdata_tableであり、私はそれがHTMLのコンテキストを返します。ヘッダデータを取得しようとすると、コードをトレースしようとすることはできませんbeautifulsoupのfind_allは、私は、ウェブサイトからのHTMLデータを取得しよう

import requests 
    from bs4 import BeautifulSoup 
    import html.parser 
    from html.parser import HTMLParser 
    import time 
    from random import randint 
    import sys 
    from IPython.display import clear_output 
    import pymysql 

links = ['https://www.ptt.cc/bbs/Gossiping/index'+str(i+1)+'.html' for i in range(10)] 
    data_links=[] 

for link in links: 
    res = requests.get(link) 
    soup = BeautifulSoup(res.text.encode("utf-8"),"html.parser") 
    data_table = soup.findAll("div",{"id":"r-ent"}) 
    print(data_table) 
+1

データをフェッチする場所からhtml構造を貼り付けることができます。また、取得要求応答から取得している「res」値も確認してください。 – min2bro

答えて

1

ブラウザでページを閲覧すると、実際のコンテンツにアクセスする前に18歳以上であることを認識して、取得しているページをhttps://www.ptt.cc/ask/over18、投稿データをyes=yesfrom = "/bbs/Gossiping/index{the_number}.html"にする必要があります。返されたソースを印刷するとフォームが表示されます。

import requests 
from bs4 import BeautifulSoup 

links = ['https://www.ptt.cc/bbs/Gossiping/index{}.html' for i in range(1,11)] 
data_links = [] 
data = {"yes":"yes"} 
head = {"User-Agent":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0"} 

for ind, link in enumerate(links, 1): 
    with requests.Session() as s: 
     data["from"] = "/bbs/Gossiping/index{}.html".format(ind) 
     s.post("https://www.ptt.cc/ask/over18", data=data, headers=head) 
     res = s.get(link, headers=head) 
     soup = BeautifulSoup(res.text,"html.parser") 
     data_divs= soup.select("div.r-ent") 
     print(data_divs) 

上記のコードは、クラスr-entであなたのすべてのdivを取得します:

<form action="/ask/over18" method="post"> 
    <input type="hidden" name="from" value="/bbs/Gossiping/index1.html"> 
    <div class="over18-button-container"> 
     <button class="btn-big" type="submit" name="yes" value="yes">我同意,我已年滿十八歲<br><small>進入</small></button> 
    </div> 
    <div class="over18-button-container"> 
     <button class="btn-big" type="submit" name="no" value="no">未滿十八歲或不同意本條款<br><small>離開</small></button> 
    </div> 
</form> 

はまた、ページ上にあるR-ENTが全くあり、唯一のdivはありません。

セッションを使用して1回だけ投稿すると、クッキーが保存されるので、次のコードが正常に動作するはずです。

links = ['https://www.ptt.cc/bbs/Gossiping/index{}.html' for i in range(1,11)] 
data_links=[] 
data = {"yes":"yes"} 
head = {"User-Agent":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0"} 
with requests.Session() as s: 
    data["from"] = "/bbs/Gossiping/index1.html" 
    s.post("https://www.ptt.cc/ask/over18", data=data, headers=head) 
    for link in links: 
     res = s.get(link, headers=head) 
     BeautifulSoup(res.text,"html.parser") 
     data_divs= soup.select("div.r-ent") 
     print(data_divs) 
関連する問題