【问题标题】:Scraping Pantip Forum using BeautifulSoup使用 BeautifulSoup 抓取 Pantip 论坛
【发布时间】:2017-02-23 17:23:06
【问题描述】:

我正在尝试从http://pantip.com/tag/Isuzu 抓取一些论坛帖子

一个这样的页面是http://pantip.com/topic/35647305

我想将每篇文章连同其作者和时间戳一起保存到一个 csv 文件中。

我正在使用 Beautiful Soup,但不可否认,我是 python 和网络抓取的初学者。我现在拥有的代码获得了必填字段,但仅适用于第一篇文章。我需要该线程上所有帖子的信息。我尝试了 soup.find_all()soup.select(),但没有得到想要的结果。

这是我正在使用的代码:

from bs4 import BeautifulSoup
import urllib2 

print "Reading URL..."
url = urllib2.urlopen("http://pantip.com/topic/35647305")
content = url.read()
soup = BeautifulSoup(content, "html.parser")

print "Finding desired HTML..."
table = soup.select("abbr.timeago")

print "\nScraped HTML is:"
print table

text = BeautifulSoup(str(table).strip(),"html.parser").get_text().encode("utf-8").replace("\n", "")
print "\nScraped text is:\n" + text

任何关于我做错了什么的线索将不胜感激。此外,欢迎任何关于如何以更好、更清洁的方式完成此操作的建议。

如前所述,我是初学者,所以请不要介意任何愚蠢的错误。 :-)

谢谢!

【问题讨论】:

  • 我认为selenium 将是解决这个问题的方法。由于很多 html 似乎是用 javascript 生成的。

标签: python html web-scraping beautifulsoup


【解决方案1】:

cmets 使用 Ajax 请求呈现:

import requests
from bs4 import BeautifulSoup

params = {"tid": "35647305", # in the url
          "type": "3"}

with requests.Session() as s:    
    s.headers.update({"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
                         "X-Requested-With": "XMLHttpRequest"})
    r = (s.get("http://pantip.com/forum/topic/render_comments", params=params))
    data = r.json() # data["comments"] contains what you want

这将为您提供所有数据。因此,您只需从每个 url 传递 tid 并更新 params dict 中的 tid。

【讨论】:

    猜你喜欢
    • 2014-03-25
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多