Skip to main content
 首页 » 编程设计

python之BeautifulSoup 返回充满变量的 HTML

2024年11月24日8jillzhang

我已经创建了一个连接到 LinkedIn 页面的链接列表。这些链接是使用 LinkedIn 的招聘人员功能(在付费专区后面)聚合的。当我将链接粘贴到我的浏览器并检查 html 代码时,它看起来很标准并且我能够轻松地识别我正在搜索的元素(见下文)。

但是,当我运行我的 python 代码并使用漂亮的汤来获取 HTML 时,返回的 HTML 与浏览器的检查元素 View 中的外观完全不同。 HTML 不是普通的标签,而是充满了变量,基本上看起来像我以前从未见过的东西(没有做过大量的抓取)。

是否有可能获得看起来像我在浏览器上看到的那样的 HTML,而不是这种看起来很疯狂的东西?这些链接是使用 recuriter 搜索功能编译的,所以我想我以某种方式使用搜索变量而不是实际结果来提取 html,但我真的不知道。

网页链接之一:https://www.linkedin.com/recruiter/profile/168561385,W0U7,CAP?searchController=smartSearch&searchId=3392867616&pos=424&total=973&searchCacheKey=f4b1a865-50e8-4f59-ba48-9dff595e63e5%2CoUbi&searchRequestId=8322c8e0-4b99-4d99-b860-1bdef1653e8c%2CXsP1&searchSessionId=3392867616&origin=PAGE&memberAuth=168561385%2CW0U7%2CCAP

这是我用来创建 html 文件的代码。我希望最后一行提取我正在寻找的数据,假设我可以获得正确的 html。

#Used to create file 
with open('departures.csv', mode='r') as csv_file: 
    csv_reader = csv.DictReader(csv_file) 
    for row in csv_reader: 
        browser.get(row['link']) 
        page = BeautifulSoup(browser.page_source, 'lxml') 
        html = page.prettify() 
        with open("output1.html", "w") as file: 
            file.write(unicode(html)) 
 
    #Code I want to Run right now it just returns an empty list 
    position = page.find_all('span', class_= 'keyword') 

当我使用浏览器转到链接时,我试图找到显示的 HTML:

<span class="keyword"> Account Manager</span> 
 
Small Piece of Actual HTML returned: <code id="profile-data" style="display: none;"> 
<!--{"breadcrumbs":{"customSearchURL":"/recruiter/smartsearch? updateSearchHistory=false&decorateHits=true&decorateFacets=false&doFacetCounting=true&searchHistoryId=3392867616&resetFacets=false&searchCacheKey=f4b1a865-50e8-4f59-ba48-9dff595e63e5%2CoUbi&searchRequestId=4d25da0f-1f73-4722-8586-9652b3f98b97%2CQSZO&doResultCaching=false&forceResultFromCache=false&origin=PPSL&doProjectBasedCounting=false&count=25&start=700","linkContext":"Controller:smartSearch,Action:search,ID:3392867616","context": 

请您参考如下方法:

LinkedIn 使用大量 JavaScript 来生成您在浏览器中看到的页面。开发人员工具中的 DOM 元素检查器向您显示该 JS 执行的当前结果,而不是浏览器下载的原始 HTML 页面。

要在浏览器中查看实际的 HTML 页面源代码,请使用查看源代码(Ctrl+U 或 Command+U)。这应该显示类似于您在 Python 中获得的 HTML。

如果您需要对最终生成的 DOM 输出进行一些抓取,您可能需要使用 headless browser可以执行 JavaScript,例如 Chrome controlled by Puppeteer .