【问题标题】:Parsing HTML using beautifulsoup gives "None"使用 beautifulsoup 解析 HTML 给出“无”
【发布时间】:2020-03-06 02:42:33
【问题描述】:

我可以清楚地看到我需要的标签,以便获取我想要抓取的数据。

根据多个教程,我的做法完全相同。

那么为什么当我只想在li 类之间显示代码时它给我“无”

from bs4 import BeautifulSoup
import requests

    response = requests.get("https://www.governmentjobs.com/careers/sdcounty")
    soup = BeautifulSoup(response.text,'html.parser')

    job = soup.find('li', attrs = {'class':'list-item'})
    print(job)

【问题讨论】:

  • 作为评论的简短回答:您只能通过该链接获取html页面,但不幸的是,内容是通过JavaScript动态插入到页面中的。这意味着您获得的页面甚至不包含这些元素。

标签: python web-scraping beautifulsoup


【解决方案1】:

虽然页面会动态更新(它会从浏览器发出额外请求以更新您在单个请求中未捕获的内容),但您可以在网络选项卡中找到感兴趣内容的源 URI。您还需要添加预期的标题。

import requests
from bs4 import BeautifulSoup as bs

headers = {'X-Requested-With': 'XMLHttpRequest'}
r = requests.get('https://www.governmentjobs.com/careers/home/index?agency=sdcounty&sort=PositionTitle&isDescendingSort=false&_=', headers=headers)
soup = bs(r.content, 'lxml')
print(len(soup.select('.list-item')))

【讨论】:

  • 谢谢@QHarr。因此,如果我像你一样做这些技巧,我可以通过检查以下链接中的 HTML 代码来进行解析:https://www.governmentjobs.com/careers/sdcounty/index??
  • soup 对象中拥有所有你需要的东西。如果需要,您可以将其写给编辑器进行检查。
  • 你可能想整理一下你的解析方式,比如在一个循环中。 for i in soup.select('.list-item'): # so something
【解决方案2】:

原始页面中没有此类内容。您所指的搜索结果是使用 JavaScript 动态/异步加载的。

打印变量response.text 以验证这一点。我使用ReqBin 得到了结果。你会发现里面没有文字list-item

不幸的是,你can't run JavaScript with BeautifulSoup

【讨论】:

  • 对不起,我是新手。你的意思是原始页面上没有内容?这将是原始页面:https://www.governmentjobs.com。但是我不需要原始页面,我需要https://www.governmentjobs.com/careers/sdcounty 页面,因为我可以看到它肯定有那个内容。
  • @Oleg:把https://www.governmentjobs.com/careers/sdcounty作为URL放在ReqBin页面上,你会发现它在原始页面上不是。你可以在浏览器中看到它,因为它是由 JavaScript 在稍后的时间点完成的,对人类来说是不明显的。
  • 谢谢。肯定学到了新东西!
【解决方案3】:

另一种处理动态加载数据的方法是使用 selenium 而不是请求来获取页面源。这应该等待 Javascript 正确加载数据,然后为您提供相应的 html。可以这样做:

from bs4 import BeautifulSoup
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options

url = "<URL>"

chrome_options = Options()  
chrome_options.add_argument("--headless") # Opens the browser up in background

with Chrome(options=chrome_options) as browser:
     browser.get(url)
     html = browser.page_source

soup = BeautifulSoup(html, 'html.parser')
job = soup.find('li', attrs = {'class':'list-item'})
print(job)

【讨论】:

    猜你喜欢
    • 2013-03-10
    • 1970-01-01
    • 2018-09-12
    • 2012-12-13
    • 2015-10-04
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多