当我尝试使用BeautifulSoup进行网络抓取时,某些HTML数据丢失了

时间:2020-07-31 13:20:58

标签: python web-scraping beautifulsoup python-requests

这是我的代码,我正尝试从该网站https://community.hackernoon.com/u/抓取数据

import requests
from bs4 import BeautifulSoup
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"}

r=requests.get("https://community.hackernoon.com/u/",headers=headers)
c=r.content

soup=BeautifulSoup(c,"html.parser")
print(soup.prettify())

当我打印soup.prettify()时,缺少一些HTML代码,因为当我尝试从该网站中查找作家的姓名时,在该HTML代码中未显示任何结果,我认为这就是为什么所有列表在输出中显示一个空列表

all=soup.find_all("div",{"id":"ember28"})
all

有人可以帮我看看有什么问题吗?

2 个答案:

答案 0 :(得分:0)

例如您的示例的某些网站不会在第一次加载时加载所有数据。

在您的示例中,它首先加载网站库,然后使用javascript加载其余信息。 (您可以通过在浏览器中禁用javascript进行测试)

您需要模拟一个浏览器(例如,使用硒)来执行网站javascript,然后在加载数据后将其抓取。

从这里开始:https://selenium-python.readthedocs.io/

答案 1 :(得分:0)

尝试:

from bs4 import BeautifulSoup as bs
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time

url = 'https://community.hackernoon.com/u/'
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.set_window_size(1024, 600)
driver.maximize_window()
driver.get(url)

soup=bs(driver.page_source,'html.parser')
time.sleep(3)
all_list=soup.find_all("span",{"class":"username"})
username_li = [user.text for user in all_list]

所有列表:

[<span class="username"><a data-user-card="daria" href="/u/daria">daria</a></span>,
 <span class="username"><a data-user-card="alexcg" href="/u/alexcg">alexcg</a></span>,
 <span class="username"><a data-user-card="daytona500-live-tv" href="/u/daytona500-live-tv">daytona500-live-tv</a></span>,
 <span class="username"><a data-user-card="David" href="/u/David">David</a></span>,
 <span class="username"><a data-user-card="kunalmishra" href="/u/kunalmishra">kunalmishra</a></span>
.
.
.
]

username_li:

['daria',
 'alexcg',
 'daytona500-live-tv',
 'David',
 'kunalmishra',
 'Hackern00n457',
 'm15o',
 'mobphone22',
 'KeyReel',
 'msarica',
 'jeffsoo2',
 'bforgan',
 'paulandre',
 'kristinamulford24',
 'hgcontent',
 'anthony1',
 'aydin.sakar',
 'jeevansirela',
 'abhikdeora',
 'ce.roso398',
 'michaeltgately',
 'SweetHeartache',
 'max',
 'jgrossman28',
 'alek.shnayder',
 'derwiki',
 'daniel.h.heyman',
 'jmuller',
 'Vadim',
 'jessekorzan',
 'PitBullCH',
 'mbroudy4',
 'kevin.pang.w',
 'tnichols',
 'arpy',
 'list_startengine',
 'pratik.ropia',
 'davidyang',
 'avantika',
 'magneticmessages',
 'ben',
 'rob',
 'doron',
 'rich.kolasa',
 'jjfleagle',
 'B17Z',
 'eugeniya.korotya',
 'will.howard',
 'colin',
 'daniel.henrique.sc']