【问题标题】:2+ Regex arguments in findall() function using beautiful soupfindall() 函数中的 2+ 正则表达式参数使用漂亮的汤
【发布时间】:2020-03-17 20:48:46
【问题描述】:

我有以下html代码

    <table width='100%' border='0' cellpadding='0' class='blackbg textheadtitle'>
        <tr>
            <td width='41%' align='left'>Title</td>
            <td width='10%' align='left'>Year</td>
            <td width='10%' align='left'>Price</td>
                <table width='99%' border='0' cellpadding='1' class="normal">
        <tr>
            <td width='41%' align='left'><strong>Quatermass 2</strong></td>
            <td width='10%' align='left'>1957</td>
            <td width='10%' align='left'>&pound;295</td>


    <table width='100%' border='0' cellpadding='0' class='blackbg textheadtitle'>
        <tr>
            <td width='41%' align='left'>Title</td>
            <td width='10%' align='left'>Year</td>
            <td width='10%' align='left'>Price</td>
                <table width='99%' border='0' cellpadding='1' class="normal">
        <tr>
            <td width='41%' align='left'><strong>Ghostbusters</strong></td>
            <td width='10%' align='left'>1985</td>
            <td width='10%' align='left'>&pound;395</td>

我只想抽出岁月

1957
1985

我已经隔离标签是“宽度”:“10%”,我可以在函数中插入一个正则表达式来忽略字符串“年份”,如下所示

from bs4 import BeautifulSoup
import requests
import re

html = ['table.html']

with open("table.html", "r") as f:
    contents = f.read()

soup = BeautifulSoup(contents, "lxml")
for name in soup.find_all("td", {"width": "10%"}, string=re.compile(r'^(?!Year$)')):
    print((name).get_text())

给我

Price
1957
£295
Price
1985
£395

但是,如果我想忽略字符串 'Price' 和任何包含 '&pound' 的字符串,我该怎么做呢?我可以输入另一个正则表达式参数吗,也许通过这样做?

for name in soup.find_all("td", {"width": "10%"},string=re.compile(r'^(?!Year$),'),(r'^(?!Price$)'),(r'^(?!&pound$)')):
    print((name).get_text())

非常感谢

【问题讨论】:

    标签: python html regex beautifulsoup tags


    【解决方案1】:

    我只想抽出岁月

    只需使用相应的正则表达式模式过滤 年份 值:

    soup = BeautifulSoup(contents, "lxml")
    for el in soup.find_all("td", {"width": "10%"}, string=re.compile(r'^\d{4}$')):
        print(el.get_text())
    

    【讨论】:

      猜你喜欢
      • 2017-06-05
      • 2012-10-12
      • 2021-12-13
      • 1970-01-01
      • 2017-04-27
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多