python - 如何在Python中忽略同一div但不同类中的文本

标签 python web-scraping beautifulsoup

我正在尝试从网站中提取日期。 html代码如下

<div class="tcell" style="width:175px;">
 <!-- status icon and date -->
 <a name="post6425787"><img alt="Old" class="inlineimg" src="https://www.f150forum.com/images/statusicon/post_old.gif"/></a>
                    12-10-2019, 06:13 PM

                    <!-- / status icon and date -->
 </div>,
 <div class="tcell">Smawgunner</div>,
 <div class="tcell" style="width:175px;">
 <!-- status icon and date -->
 <a name="post6425799"><img alt="Old" class="inlineimg" src="https://www.f150forum.com/images/statusicon/post_old.gif"/></a>
                    12-10-2019, 06:18 PM

                    <!-- / status icon and date -->
 </div>,
 <div class="tcell">CKsBAT</div>

我想通过忽略名称字段来仅提取日期。我的代码如下

date = posts.find_all(lambda tag: tag.name == 'div' and 
                                   tag.get('class') == ['tcell'])
for i in date:
    print(i.text)

上面的代码给出了日期和名称。如何从 HTML 代码中仅获取日期?预先感谢您

最佳答案

最直接的是,您可以使用 select:nth-child(odd):

from bs4 import BeautifulSoup 

html = """
<div>
  <div class="tcell" style="width:175px;">
    <a name="post6425787">
      <img alt="Old" 
           class="inlineimg" 
           src="https://www.f150forum.com/images/statusicon/post_old.gif"
      />
    </a>
                       12-10-2019, 06:13 PM
  </div>,
  <div class="tcell">Smawgunner</div>,

  <div class="tcell" style="width:175px;">
    <a name="post6425799">
      <img alt="Old" 
           class="inlineimg" 
           src="https://www.f150forum.com/images/statusicon/post_old.gif"
      />
    </a>
                     12-10-2019, 06:18 PM
  </div>,
  <div class="tcell">CKsBAT</div>
</div>
"""

soup = BeautifulSoup(html, "lxml")

for x in soup.select("div.tcell:nth-child(odd)"):
    print(x.text.strip())

输出:

12-10-2019, 06:13 PM
12-10-2019, 06:18 PM

如果您需要基于内容性质的精度,您可以使用与您的日期格式完全匹配的正则表达式(除了空格之外什么都没有包围;根据需要放松正则表达式):

import re

soup = BeautifulSoup(html, "lxml")
pattern = r"^\s*(\d\d-){2}\d{4}, \d\d:\d\d [AP]M\s*$"

for x in soup.find_all(text=re.compile(pattern)):
    print(x.strip())

如果您的日期格式不确定并且您想要获取任何可以解析为日期的内容:

from dateutil.parser import parse as parse_date

soup = BeautifulSoup(html, "lxml")

def try_parse_date(s):
    try: return parse_date(s, fuzzy=True)
    except ValueError: pass

for x in soup.find_all(text=try_parse_date):
    print(x.strip())

关于python - 如何在Python中忽略同一div但不同类中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59651872/

相关文章:

python - 从监听套接字/HTTPServer 获取传入 URL

python - BeautifulSoup 无法从 wiki 中提取表格

python - 美丽汤网页抓取 : How do i scrape this particular html structure

python - BeautifulSoup 如何在 <br> 标签后提取文本

python - 为什么 import pygame_textinput 不起作用?

python - 如何在 Python 中使用 PhantomJS 清除 Selenium 中的缓存和 cookie?

python - 在 Cython 中迭代字节/unicode 字符串的最佳方法

Python:谷歌搜索结果抓取

python - 从 Twitter XML 页面提取数据的列表问题

python - 如何找到使用 Python urllib2 和漂亮的汤库的任何网页的推文/Facebook 数量?