【问题标题】:Python scrape specific tag without class namePython抓取没有类名的特定标签
【发布时间】:2017-05-15 08:44:04
【问题描述】:

我正在开发一个 python 脚本来从特定站点抓取数据。 我正在使用 Beautiful Soap 作为 python 模块。 HTML 页面中有趣的数据都在这个结构中:

<tbody aria-live="polite" aria-relevant="all">
  <tr  style="">
   <td>
      <a href="www.server.com/art/crag">Name<a>
   </td>
   <td class="nowrap"></td>
   <td class="hidden-xs"></td>
  </tr>
</tbody>

在标签 tbody 中还有更多的 tr 标签,我想对每个标签 td 的第一个标签 a 进行处理

我试过这样:

page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
a = soup.find(id='tabella_falist')
b = a.find("tbody")
link = [p.attrs['href'] for p in b.select("a")]

但是通过这种方式,脚本会将所有 href 放入所有 td 标记中。怎么可能只取第一?

谢谢

【问题讨论】:

标签: python web-scraping beautifulsoup


【解决方案1】:

如果我理解正确,你可以试试这个:

from bs4 import BeautifulSoup
import requests

url = 'your_url'
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')

print(soup.a)

soup.a 将返回页面上的第一个 a 标记。

【讨论】:

  • 是的,但我会将第一个 a 标签检索到 td 标签中。 td 标签在 tr 标签中,并且在 tbody 标签中还有更多 tr 标签
  • 这样我取第一个标签a,但是我想要一个tr列表的第一个标签a
【解决方案2】:

这应该做的工作

html = '''<html><body><tbody aria-live="polite" aria-relevant="all">
  <tr  style="">
   <td>
      <a href="www.server.com/art/crag">GOOD ONE<a>
      <a href="www.server.com/art/crag">NOT GOOD ONE<a>
   </td>
   <td class="nowrap">
      <a href="#">GOOD ONE</a>
   </td>
   <td class="hidden-xs"></td>
  </tr>
</tbody></body></html>'''

from bs4 import BeautifulSoup
soup = BeautifulSoup(html)

for td in soup.select('td'):
    a = td.find('a')
    if a is not None:
        print a.attrs['href']

【讨论】:

    猜你喜欢
    • 2022-11-22
    • 2013-07-26
    • 2011-08-27
    • 2018-06-30
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    相关资源
    最近更新 更多