【问题标题】:Find elements with BeautifulSoup in a HTML在 HTML 中使用 BeautifulSoup 查找元素
【发布时间】:2018-07-09 13:44:21
【问题描述】:

我需要在我的 html 代码中找到所有元素为 <td alert="0" op="0" class=" es_numero cell_imps24ad"><span>1.204</span></td>。我不能发送所有的 html 代码,因为它是机密信息。

我正在尝试使用此代码:

# encoding=utf8
# -*- coding: utf-8 -*-
import random
import requests
from requests.auth import HTTPBasicAuth
import sys
import csv
from bs4 import BeautifulSoup


reload(sys)
sys.setdefaultencoding('utf-8')
lista = []
number = str(random.random())

user = ''
passwd = ''
url = ''
login = requests.get(url, auth=HTTPBasicAuth(user, passwd))
url_sitios = ''

sitios = requests.get(url_sitios, auth=HTTPBasicAuth(user, passwd))
sitios2 = sitios.text
html = sitios2
soup = BeautifulSoup(html)

for item in soup.find_all("td", {"class": " es_numero cell_imps24ad"}):
    print item.text, item.next_sibling

我想要的输出是这样的: es_numero cell_imps24ad : 1.204

【问题讨论】:

  • soup.find_all("td", {"class": " es_numero cell_imps24ad"}) 在这种情况下应该是正确的。你收到什么输出而不是es_numero cell_imps24ad : 1.204
  • 我做的时候什么也没收到!所以,我不明白为什么我不能提取它。 @Ajax1234

标签: python html beautifulsoup


【解决方案1】:

您需要将解析类型传递给BeautifulSoup

soup = BeautifulSoup(html, 'lxml') #add the 'lxml' parser
for item in soup.find_all("td", {"class": " es_numero cell_imps24ad"}):
   print item.text, item.next_sibling

编辑:鉴于nombreurl 标记的html,你可以试试这个:

from bs4 import BeautifulSoup as soup
import re
s = "<url>https://www.google.com.ar/</url>\n<nombre>google.com.ar‌​</nombre>"
data = map(lambda x:x.text, soup(s, 'lxml').find_all(re.compile('nombre|url')))

输出:

[u'https://www.google.com.ar/', u'google.com.ar\u200c\u200b']

编辑 2:对于较小的提取:

from bs4 import BeautifulSoup as soup
s = '<ultimas24hrs> <item id="imps24ad">0</item>'
new_s = soup(s, 'lxml')
the_id = int(new_s.find('item', {'id':"imps24ad"}).text)

【讨论】:

  • 我的结果和以前一样...[]
  • @MartinBouhier 网站也可能是动态的,即脚本在页面加载后会使用数据填充页面。如果是这种情况,那么您将不得不使用浏览器操作工具,例如 selenium
  • 我用另一个 url 解决了,xml instaed of html...我现在唯一需要的问题是如果我想提取 nombreurlfor item in soup.find_all('nombre', 'url'): 没有工作.. . 我需要怎么做?
  • nombreurl 是什么?想要的文本,或者标签和类?
  • 类似这样的东西:&lt;url&gt;https://www.google.com.ar/&lt;/url&gt;\n&lt;nombre&gt;google.com.ar&lt;/nombre&gt;,当我使用for item in soup.find_all( 'url'):我有https://www.google.com.ar 答案,当我使用nombre and url 时,我无法提取这两个元素
猜你喜欢
  • 1970-01-01
  • 2017-03-08
  • 2021-10-15
  • 1970-01-01
  • 2020-10-11
  • 2023-02-06
  • 2021-12-27
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多