programing

모든 엔트리를 한 번에 무한 스크롤로 로드하여 python의 HTML을 구문 분석하는 방법

codeshow 2023. 3. 13. 20:42
반응형

모든 엔트리를 한 번에 무한 스크롤로 로드하여 python의 HTML을 구문 분석하는 방법

페이지에서 정보를 추출하려고 합니다.이 페이지는 한 번에 10개의 항목을 로드하며 모든 항목을 로드하려면 스크롤해야 합니다(총 100개).HTML을 해석하여 처음 10개의 엔트리에 필요한 정보를 얻을 수 있지만 HTML을 해석하기 전에 모든 엔트리를 완전히 로드하고 싶습니다.

python, requests, BeautifulSoup을 사용하고 있습니다.페이지가 처음 10개의 엔트리와 함께 로드될 때 해석하는 방법은 다음과 같습니다.

from bs4 import BeautifulSoup
import requests
s = requests.Session()
r = s.get('https://medium.com/top-100/december-2013')
page = BeautifulSoup(r.text)

그러나 이것은 처음 10개의 엔트리만 로드합니다.페이지를 보고 후속 엔트리를 로드하기 위해 사용되는 AJAX 요청을 받았습니다만, JSON을 해석하는 대신 HTML 파서를 사용하는 것이 좋습니다.코드는 다음과 같습니다.

from bs4 import BeautifulSoup
import requests
import json
s = requests.Session()
url = 'https://medium.com/top-100/december-2013/load-more'
payload = {"count":100}
r = s.post(url, data=payload)
page = json.loads(r.text[16:]) #skip some chars that throw json off

이것은 나에게 데이터를 주지만 그것은 매우 길고 복잡한 JSON에 있습니다. 나는 페이지의 모든 데이터를 로드하고 HTML을 단순히 해석하는 것이 좋습니다. 또한 렌더링된 HTML은 JSON 응답보다 더 많은 정보를 제공합니다(즉, 불분명한 사용자 대신 작성자의 이름).아이디 등)여기에도 비슷한 질문이 있었지만 관련된 답변은 없었다.이상적으로는 POST 콜을 발신하여 HTML을 요청하여 해석하고 싶은데, 할 수 없었습니다.

이 작업은 요청 및 BeautifulSoup에서 수행할 수 없습니다. 스크롤 다운 시 나머지 엔트리를 로드하는 페이지에서 수행할 수 없습니다.실제 브라우저를 열고 키 누르기 이벤트를 프로그래밍 방식으로 페이지 아래로 전달할 수 있는 셀레늄을 사용하여 이 작업을 수행할 수 있습니다.이 비디오를 보고 액션을 확인하십시오.http://www.youtube.com/watch?v=g54xYVMojos

http://www.tidbitsofprogramming.com/2014/02/crawling-website-that-loads-content.html

아래는 셀레늄을 사용하여 100개의 포스트 제목을 모두 추출하는 스크립트입니다.

import time

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome()

browser.get("https://medium.com/top-100/december-2013")
time.sleep(1)

elem = browser.find_element_by_tag_name("body")

no_of_pagedowns = 20

while no_of_pagedowns:
    elem.send_keys(Keys.PAGE_DOWN)
    time.sleep(0.2)
    no_of_pagedowns-=1

post_elems = browser.find_elements_by_class_name("post-item-title")

for post in post_elems:
    print post.text

출력:

When Your Mother Says She’s Fat
When “Life Hacking” Is Really White Privilege
As tendências culturais dos anos 2000 adiantadas pelo É o Tchan na década de 90
Coming Out as Biracial
Como ganhar discussões com seus parentes de direita neste Natal
How to save local bookstores in two easy steps
Welcome to Dinovember
How to Piss Off Your Barista
The boy whose brain could unlock autism
CrossFit’s Dirty Little Secret
Welcome to Medium
Here’s How the Military Wasted Your Money in 2013
Why I Wear Nail Polish
The day of High School I’ll never forget
7 Reasons Buffalonians Shouldn’t Hate Snow
Dear Guy Who Just Made My Burrito:
Is the Mona Lisa Priceless?
Please stop live tweeting people’s private conversations
Your Friends and Rapists
Eight things you can live without
The Value of Content
40 Ways To Make Life Simple Again
Manila-Beijing-Washington:
Things I Wish Someone Had Told Me When I Was Learning How to Code
Dear Ticketmaster,
Steve Jobs Danced To My Song
11 Things I Wish I Knew When I Started My Business
Bullish: Benevolent Sexism and “That Guy” Who Makes Everything Awkward
Advice to a College Music Student
Silver Gyninen joutui sotaan
Imagining the Post-Antibiotics Future
Which side are you on?
Put it away, junior. 
Casual Predation
The sad little iPhone commercial
How Node.js is Going to Replace JavaScript
Why you should have your heart broken into a million little pieces. 
How to Write Emails Like a CEO
Designing Products That Scale
How radioactive poison became the assassin’s weapon of choice
Why do people hate CrossFit?
We (Still) Need Feminism
10 Advanced Hearthstone Arena Tips
Let It Full-Bleed
What Medium Is For
How a Small Force of Finnish Ski Troops Fought Off a Massive Soviet Army
An Introvert’s Guide to Better Presentations
Mandela The Terrorist
Why You Should have a Messy Desk
Why I’m Not a TEDx Speaker
Fonts have feelings too
You Don’t Want Your Thanksgiving to Go Like This
What I’ve Learned in My First Month as a VC
Why Quantity Should be Your Priority
My Airbnb story
I Wanna Date You Like An Animal
The GIF Guide to Getting Paid
How We Discovered the Underground Chinese App Market
First Images of a Heart Injected with Liquid Metal 
Beyonce Broke the Music Business
“View mode” approach to responsive web design
Sometimes You Will Forget Your Mom Has Cancer
Darkness Ray Beams Invisibility From A Distance
Why Work As We Know It May Be Immoral
Staying Ahead of the Curve
The Geekiest Game Ever Made Has Been Released In Germany 
The Dirty Secret Behind the Salesforce $1M Hackathon
I’m a really good impostor
Mathematical Model of Zombie Epidemics Reveals Two Types of Living-Dead Infections
The Heartbreak Kid
200 Things
I’m Not Racist But—
Duel of the Superbattleships
23 and You
The Seattle NO
I’m a vaccine refuser. There, I said it. 
The Year We Broke Everything
How to make a DIY home alarm system with a raspberry pi and a webcam
Strike While the App is Hot
How to Fall In (and Out) of Love:
Why did Google make an ad for promoting “Search” in India where it has over 97% market share?
A Holiday Message From Jesus
Revealed: The Soviet Union’s $1 Billion ‘Psychotronic’ Arms Race with the US
Postmortem of a Venture-backed Startup
The 1.x Crore Myth
The “Getting Shit Done” Sleep Cycle 
Is the F-35 Joint Strike Fighter the New F-4?
Can the F-35 Win a Dogfight?
Responsive Photosets
Fightball: Millennials vs Boomers
The iconicity of “peaceful resistance”
How We Make Chocolate
Five Ships of the Chinese Navy You Really Ought to Know About
Glassholes and Black Rock City
Bad News for U.S. Warplane Pilots: Russia’s New Dogfighting Missile Can’t Miss
How Antisec Died
10 ways you’ll probably f**k up your startup
UPDATED: Finding the unjustly homeless, and teaching them to code.
Technology hasn’t Changed Us.
What I’ve learned from fatherhood 

다음과 같이 시험해 볼 수 있습니다.

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait

pause = 10
driver = webdriver.PhantomJS(executable_path='phantomjs.exe')
driver.get("your_url")
#This code will scroll down to the end
while True:
     try:
        # Action scroll down
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
     break
 except: 
     pass

또는 이 질문에서 Andrew Che가 제시한 답변을 시도해 볼 수도 있습니다.이것은 3년 전의 질문으로, 페이지는 없어졌습니다만, 스크롤 결과 페이지(예를 들면 「톱」을 검색했습니다)를 사용해 같은 것을 시도하면, 결과 리스트의 다른 페이지를 취득하기 위해서 호출할 수 있는 엔드 포인트를 찾을 수 있습니다.이 경우는 「https://medium.com/search/posts?q=top&page=1'」입니다.

언급URL : https://stackoverflow.com/questions/21006940/how-to-load-all-entries-in-an-infinite-scroll-at-once-to-parse-the-html-in-pytho

반응형