【问题标题】:Python, How to parse HTML from URL?Python,如何从 URL 解析 HTML?
【发布时间】:2020-11-26 10:28:18
【问题描述】:

我有 Python 代码,可以从包含 HTML 代码的字符串变量中解析数据。

我想要从 URL 获取 HTML 然后解析这些数据的代码。

工作代码(解析 HTML):

from bs4 import BeautifulSoup

data = '''\
<html>
  <head>
    <meta name="generator"
     content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy- 
      html5/tree/c63cc39" />
    <title></title>
   </head>
 <body>
<div class="Eqh F6l Jea k1A zI7 iyn Hsu">
  <div class="Shl zI7 iyn Hsu">
    <a data-test-id="search-guide" href="" title="Search for &quot;living room colors&quot;">
      <div class="Jea Lfz XiG fZz gjz qDf zI7 iyn Hsu" style="white-space: nowrap; background-color: 
         rgb(162, 152, 139);">
        <div class="tBJ dyH iFc MF7 erh tg7 IZT mWe">Living</div>
       </div>
      </a>
     </div>
    </div>
  </body>
 </html>
 '''
soup = BeautifulSoup(data, 'html.parser')
a = soup.select('div.Eqh.F6l.Jea.k1A.zI7.iyn.Hsu a')[0]
print(a['title'])

这是我尝试过但不起作用的方法(从 URL 获取 HTML 然后解析):

import requests
from bs4 import BeautifulSoup

vgm_url = 'https://www.pinterest.com/search/pins/?q=skin%20care'
html_text = requests.get(vgm_url).text
soup = BeautifulSoup(html_text, 'html.parser')
a = soup.select('div.Eqh.F6l.Jea.k1A.zI7.iyn.Hsu a')
for a in soup.select('div.Eqh.F6l.Jea.k1A.zI7.iyn.Hsu a'):
    print(a['title'])

我没有收到任何错误,它不打印任何内容。 感谢您的帮助。

【问题讨论】:

  • 真的确定html_text有你想要的文字吗?也就是说,它包含您想要的内容,而不是登录页面?

标签: python html-parsing


【解决方案1】:

然后在调试过程中使用print(html_text) 看看你得到了什么;)。

当您打印它时,您会看到它与页面源不同(在 Chrome 或其他网络浏览器中查看它并转到 url)。当您在浏览器中访问该页面时,您还可以看到该页面正在加载一段时间。

因此,您需要等待它加载类似Selenium 的内容。

为了演示一点 Selenium,我加载了您的页面并单击了带有定义类的东西,该类在一段时间后加载:

# you will have to install (Chrome), or another browser driver
from selenium.webdriver import Chrome

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = Chrome(r'C:\Program Files\chromedriver.exe')  # I have (Chrome) installed here

driver.get("https://www.pinterest.com/search/pins/?q=skin%20care")
feeling_lucky_btn = WebDriverWait(driver, 3).until(  # waiting for loading
    EC.presence_of_element_located(
    (By.CLASS_NAME, 'GrowthUnauthPinImage__Image')))  # identifiing element by class name
feeling_lucky_btn.click()

【讨论】:

  • 感谢您的回复,是的,但我想要正确的结果,代码的结果,只是打印出长的 HTML 代码不会解决我的问题,除非你有关于如何的提示使用它。
  • 如果html_textdata 相同(您的示例),并且您的示例有效,那么您尝试的也必须有效,对吧?
  • 感谢您的回复,我在看打印结果,HTML代码很长,没有应该的代码,我现在很困惑。
  • @Brambor requests 甚至可以做到这一点吗?我认为他需要使用selenium?不是吗?我看到他的汤里只有 1 个主 div。没有别的了。
  • @Dave99 我在我的回答中添加了 Selenium 的演示 ;)。
猜你喜欢
  • 2016-08-12
  • 1970-01-01
  • 2011-07-06
  • 2012-10-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2018-12-03
  • 1970-01-01
相关资源
最近更新 更多