提取刮下的漂亮的soap HTML d

2024-03-29 10:37:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用BeautifulSoap和Python从this website 中提取数据 我已经使用find\u all提取了表中的表行,现在我想提取每行的表数据,并将每行数据作为数组中的行添加。例如:

[12:55, Beverello, Ischia, http://alilauronew.forth-crs.gr/italian_b2c 
/npgres.exe?PM=BM;...., ....]

任何关于如何做的帮助都是欢迎的。 这是提取数据的示例:

   [<tr class="grey1">
        <td class="orario">12:55</td>
        <td class="aL">Beverello</td>
        <td class="aL">Ischia</td>
        <td>
            <div class="circle green">
               <span class="tt-container">
                   <span class="tt-arrow"></span>
                   <span class="tt-text">corsa regolare</span>
               </span>
            </div>
        </td>
       <td><a href="http://alilauronew.forth-crs.gr/italian_b2c     
            /npgres.exe?PM=BM" target="_blank"><img src="/templates 
            /frontend/images/carrello.png"/></a></td>
 </tr>
   [<tr class="grey1">
        <td class="orario">14:45</td>
        <td class="aL">Ischia</td>
        <td class="aL">Beverello</td>
        <td>
            <div class="circle green">
               <span class="tt-container">
                   <span class="tt-arrow"></span>
                   <span class="tt-text">corsa regolare</span>
               </span>
            </div>
        </td>
       <td><a href="http://alilauronew.forth-crs.gr/italian_b2c     
            /npgres.exe?PM=BM" target="_blank"><img src="/templates 
            /frontend/images/carrello.png"/></a></td>
 </tr>

Tags: 数据divhttptrclasstdspanal
2条回答

下面是一个完整的工作示例,data列表将包含您想要的所有内容,而没有杂音(空字符串等)

import requests
from bs4 import BeautifulSoup

response = requests.get('http://www.alilauro.it').text
bs = BeautifulSoup(response)

data = []
# I don't want to scrape the headers, so I'm slicing the list, emitting the first element
no_header = list(bs.select('#partenze tr'))[1:]
for tr in no_header:
    td = tr.select('td')
    data.append({
        'ORA':td[0].text,
        'PARTENZA DA':td[1].text,
        'ARRIVO A':td[2].text,
        'ACQUISTA':td[4].select('a')[0].attrs['href']
    })

print(data)

注意事项:

  • 我使用requests库发出http请求,您可以使用任何您想要的东西
  • 我使用css选择器,使用bs的内置select只是个人选择
from bs4 import BeautifulSoup
html="""
<tr class="grey1">
        <td class="orario">12:55</td>
        <td class="aL">Beverello</td>
        <td class="aL">Ischia</td>
        <td>
            <div class="circle green">
               <span class="tt-container">
                   <span class="tt-arrow"></span>
                   <span class="tt-text">corsa regolare</span>
               </span>
            </div>
        </td>
       <td><a href="http://alilauronew.forth-crs.gr/italian_b2c
            /npgres.exe?PM=BM" target="_blank"><img src="/templates
            /frontend/images/carrello.png"/></a></td>
 </tr>
"""
soup = BeautifulSoup(html, "lxml")
row=[td.text.strip() for td in soup.findAll('td')]
print(row)

输出:

['12:55', 'Beverello', 'Ischia', 'corsa regolare', '']

相关问题 更多 >