【问题标题】:Extract Colored Text from Table with BeautifulSoup使用 BeautifulSoup 从表格中提取彩色文本
【发布时间】:2021-01-20 14:00:54
【问题描述】:

我是 Python 新手,对一般的编程也很陌生。我正在尝试编写一个脚本,该脚本使用 BeautifulSoup 解析 https://www.state.nj.us/mvc/ 的任何红色文本。我看的表格是比较简单的HTML:

<html>
 <body>
  <div class="alert alert-warning alert-dismissable" role="alert">
   <div class="table-responsive">
    <table class="table table-sm" align="center" cellpadding="0" cellspacing="0">
     <tbody>
      <tr>
       <td width="24%">
        <strong>
         <font color="red">Bakers Basin</font>
        </strong>
       </td>
       <td width="24%">
        <strong>Oakland</strong>
       </td>
 ...
 ...
 ...
      </tr>
     </tbody>
    </table>
   </div>
  </div>
 </body>
</html>

例如,从上面我想找到贝克斯盆地,而不是奥克兰。

这是我编写的 Python(改编自 Cory Althoff The Self-Taught Programmer,2017,Triangle Connection LCC):

import urllib.request
from bs4 import BeautifulSoup


class Scraper:
    def __init__(self, site):
        self.site = site

    def scrape(self):
        r = urllib.request.urlopen(self.site)
        html = r.read()
        parser = "html.parser"
        soup = BeautifulSoup(html, parser)
        tabledmv = soup.find_all("font color=\"red\"")
        for tag in tabledmv:
            print("\n" + tabledmv.get_text())


website = "https://www.state.nj.us/mvc/"
Scraper(website).scrape()

我似乎在这里遗漏了一些东西,因为我似乎无法让它刮过桌子并返回任何有用的东西。最终结果是我想添加时间模块并每 X 分钟运行一次,然后让它在某处记录每个站点变红时的消息。 (这一切都是为了让我的妻子找出新泽西最不拥挤的 DMV!)。

非常感谢任何有关让 BeautifulSoup 工作的帮助或指导。

【问题讨论】:

  • 试试这个:soup.find_all('font[color="red"]')。见:MDN - Attribute selectors
  • @Mr.Polywhirl CSS 选择器的语法是soup.select()
  • 我发现了我的问题 - 似乎这个页面有一个隐藏 HTML 其余部分的元素。我得想办法解决这个问题。
  • Try Selenium。看起来您正在等待内容动态加载。

标签: python html web-scraping beautifulsoup


【解决方案1】:

该表实际上是从this 站点加载的。

要仅获取红色文本,您可以将 CSS 选择器 soup.select('font[color="red"]') 用作 @Mr。 Polywhirl 提到:

import urllib.request
from bs4 import BeautifulSoup


class Scraper:
    def __init__(self, site):
        self.site = site

    def scrape(self):
        r = urllib.request.urlopen(self.site)
        html = r.read()
        parser = "html.parser"
        soup = BeautifulSoup(html, parser)
        tabledmv = soup.select('font[color="red"]')[1:]
        for tag in tabledmv:
            print(tag.get_text())


website = "https://www.state.nj.us/mvc/locations/agency.htm"
Scraper(website).scrape()

【讨论】:

  • 谢谢,这正是我的问题。就一个问题:[1:]在select方法tabledmv = soup.select('font[color="red"]')[1:]中做了什么
  • 如果你从输出中删除[1:],你会看到文本RED会被打印出来,因为我们不想这样,我们使用list slicing
【解决方案2】:

数据是从其他位置加载的,在本例中为 'https://www.state.nj.us/mvc/locations/agency.htm'。要获取每个城镇的城镇+标题,您可以使用以下示例:

import requests 
from bs4 import BeautifulSoup


url = 'https://www.state.nj.us/mvc/locations/agency.htm'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

for t in soup.select('td:has(font)'):
    i = t.find_previous('tr').select('td').index(t)
    if i < 2:
        print('{:<20} {}'.format(' '.join(t.text.split()), 'Licensing Centers'))
    else:
        print('{:<20} {}'.format(' '.join(t.text.split()), 'Vehicle Centers'))

打印:

Bakers Basin         Licensing Centers
Cherry Hill          Vehicle Centers
Springfield          Vehicle Centers
Bayonne              Licensing Centers
Paterson             Licensing Centers
East Orange          Vehicle Centers
Trenton              Vehicle Centers
Rahway               Licensing Centers
Hazlet               Vehicle Centers
Turnersville         Vehicle Centers
Jersey City          Vehicle Centers
Wallington           Vehicle Centers
Delanco              Licensing Centers
Lakewood             Vehicle Centers
Washington           Vehicle Centers
Eatontown            Licensing Centers
Edison               Licensing Centers
Toms River           Licensing Centers
Newton               Vehicle Centers
Freehold             Licensing Centers
Runnemede            Vehicle Centers
Newark               Licensing Centers
S. Brunswick         Vehicle Centers

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多