【发布时间】:2022-06-11 03:16:20
【问题描述】:
借助一点 Python 知识,我尝试抓取一些 LinkedIn 公司的帖子。
使用我从this website 获取的以下代码,在提取其内容之前首先找到公司LinkedIn 页面上的所有帖子。问题是我知道,我计算过,无论我使用的是 lxml、html5lib 或 html.parser 中的哪一个解析器,都比 findAll 函数返回的帖子多。在一种情况下,它会返回 67 个帖子中的 43 个,在另一种情况下,它会返回 14 个帖子中的 10 个。通常,它会找到大约 3 或 4 个,然后跳过 4 或 5 个帖子,然后再次找到一些,等等。
我怎样才能知道为什么会发生这种情况?
#!/usr/bin/env python
# coding: utf-8
# Import
from selenium import webdriver
from bs4 import BeautifulSoup as bs
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
# Get credentials to log in to LinkedIn
username = input('Enter your linkedin username: ')
password = input('Enter your linkedin password: ')
company_name = input('Name of the company: ')
# Access Webdriver
s=Service(ChromeDriverManager().install())
browser = webdriver.Chrome(service=s)
browser.maximize_window()
# Define page to open
page = "https://www.linkedin.com/company/{}/posts/?feedView=all".format(company_name)
# Open login page
browser.get('https://www.linkedin.com/login?fromSignIn=true&trk=guest_homepage-basic_nav-header-signin')
# Enter login info:
elementID = browser.find_element_by_id('username')
elementID.send_keys(username)
elementID = browser.find_element_by_id('password')
elementID.send_keys(password)
elementID.submit()
# Go to webpage
browser.get(page + 'posts/')
# Define scrolling time
SCROLL_PAUSE_TIME = 1.5
# Get scroll height
last_height = browser.execute_script("return document.body.scrollHeight")
# Scroll all the way to the bottom of the page
while True:
# Scroll down to bottom
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
# Calculate new scroll height and compare with last scroll height
new_height = browser.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
# Get content of page
content = browser.page_source.encode('utf-8').strip()
# Create soup
linkedin_soup = bs(content, "html5lib")
linkedin_soup.prettify()
# Find entities that contain posts
containers = linkedin_soup.findAll("div",{"class":"occludable-update ember-view"})
【问题讨论】:
-
哪家公司给你 14 个中的 10 个,所以我可以调试/测试它。
-
如果你使用的是pyCharm这样好的IDE,内置的调试器应该可以帮到你。
-
10/14 是 taniq。我正在使用也有调试器的 Visual Studio,我一直在使用它,但找不到原因。
-
@chitown88 你有机会尝试调试吗?我真的很感激!如果你用 taniq 替换
company_name我相信它应该可以工作,否则请告诉我。 -
哦不,我没有。我没有意识到你在评论中回复了。我今天会这样做。
标签: python html selenium selenium-webdriver beautifulsoup