Python 使用 beautifulsoup 从复杂的论坛中抓取最后发布日期

标签 python web-scraping beautifulsoup

所以我试图从论坛中抓取一些数据(特别是上一篇文章的日期),与这个确切的论坛的其他元素一起工作得很好,但是日期元素具有 super 奇怪的类,无论我添加多少元素,我不能专门针对它只获取一次..

这是我的代码片段,用于仅获取上次帖子的日期。

import re
import urllib
import os

from bs4 import BeautifulSoup
from pip._vendor import requests


def make_soup(url):
   thepage = urllib.request.urlopen(url)
   soupdata = BeautifulSoup(thepage, "html.parser")
   return soupdata

soup2 = make_soup('http://forums.automotive.com/69/1052/general-auto-repair/page1.html')

lPostDate = ""

for postDate2 in soup2.findAll('td', {"class": "brdr1 pad10_20 bgrnd19"}):
    lPostDate += (postDate2.get_text("\n", strip=True)[0:10] + "\n")
    print(lPostDate)

但是这是我每次的输出:

10/06/15 0

10/06/15 0
137

10/06/15 0
137
49976

10/06/15 0
137
49976
02/04/17 1

10/06/15 0
137
49976
02/04/17 1
1

10/06/15 0
137
49976
02/04/17 1
1
130

10/06/15 0
137
49976
02/04/17 1
1
130
01/30/17 0

10/06/15 0
137
49976
02/04/17 1
1
130
01/30/17 0
0

10/06/15 0
137
49976
02/04/17 1
1
130
01/30/17 0
0
145

这将持续 1080 行...任何提示将不胜感激。使用“re.compile”在另一个论坛上完成此操作,效果非常好,但是这个论坛在命名其元素时更加挑剔。

最佳答案

for tr in soup2.findAll('tr', id=re.compile('Thread')):
    text = tr('td')[2].get_text(strip=True)
    date = text.split('By')[0]  # strip the By:...
    print(date)

输出:

10/06/15 05:47 PM
02/04/17 11:58 PM
01/30/17 08:44 PM
01/26/17 12:44 AM
01/22/17 06:25 PM
01/19/17 02:23 PM
01/18/17 10:52 PM
01/18/17 04:57 PM
01/17/17 04:15 PM
01/17/17 04:12 PM
01/14/17 08:34 PM
01/12/17 08:00 PM
01/10/17 02:21 PM
01/10/17 01:00 PM
01/08/17 11:45 PM

关于Python 使用 beautifulsoup 从复杂的论坛中抓取最后发布日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42096856/

相关文章:

python - 如何在openkinect中停止和启动kinect?

javascript - Web 抓取提取 Javascript 表 Selenium+Python

web-scraping - 获取reddit数据

r - R 中的网页抓取, "... does not exist in current working directory"错误

python - 在编译这样的代码时出现错误 'NoneType' 对象没有属性 'find_all'

python - 在 CentOS 中将 python 3 设置为默认 python 版本

python - 使用标签和索引在 pandas 数据框中设置值,现在 ix 已弃用

python - 为什么我的列表有额外的双括号?

python - 使用 python 获取 YouTube 播放列表网址

python - HTML 解析没有响应