아름다운 수프 긁기

Sep 30 2020

이전 작업 코드가 더 이상 올바르게 작동하지 않는 문제가 있습니다.

내 파이썬 코드는 아름다운 수프를 사용하여 웹 사이트를 스크랩하고 이벤트 데이터 (날짜, 이벤트, 링크)를 추출합니다.

내 코드는에있는 모든 이벤트를 가져옵니다 tbody. 각 이벤트는 <tr class="Box">. 문제는 내 스크레이퍼 <tr style ="box-shadow: none;>가이 섹션 (내가 스크래핑하고 싶지 않은 이벤트에 대한 사이트에 3 개의 광고가 포함 된 섹션)에 도달하면 <tr class="Box">. 이 tr 스타일을 건너 뛰거나 향후 케이스를 무시하는 방법이 있습니까?

import pandas as pd
import bs4 as bs
from bs4 import BeautifulSoup
import urllib.request
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module='bs4')

source = urllib.request.urlopen('https://10times.com/losangeles-us/technology/conferences').read()
soup = bs.BeautifulSoup(source,'html.parser')
   #---Get Event Data---
    test1=[]
    table = soup.find('tbody')
    table_rows = table.find_all('tr') #find table rows (tr)
    for x in table_rows:   
        data = x.find_all('td')  #find table data
        row = [x.text for x in data]
        if len(row) > 2: #Exlcudes rows with only event name/link, but no data.
            test1.append(row)
test1

답변

2 AndrejKesely Sep 30 2020 at 01:56

데이터는 JavaScript를 통해 동적으로로드되므로 더 많은 결과를 볼 수 없습니다. 이 예제를 사용하여 더 많은 페이지를로드 할 수 있습니다.

import requests
from bs4 import BeautifulSoup


url = "https://10times.com/ajax?for=scroll&path=/losangeles-us/technology/conferences"
params = {"page": 1, "ajax": 1}
headers = {"X-Requested-With": "XMLHttpRequest"}

for params["page"] in range(1, 4):  # <-- increase number of pages here
    print("Page {}..".format(params["page"]))
    soup = BeautifulSoup(
        requests.get(url, headers=headers, params=params).content,
        "html.parser",
    )
    for tr in soup.select('tr[class="box"]'):
        tds = [td.get_text(strip=True, separator=" ") for td in tr.select("td")]
        print(tds)

인쇄물:

Page 1..
['Tue, 29 Sep - Thu, 01 Oct 2020', 'Lens Los Angeles', 'Intercontinental Los Angeles Downtown, Los Angeles', 'LENS brings together the entire Degreed community - our clients, invited prospective clients, thought leaders, partners, employees, executives, and industry experts for two days of discussion, workshops,...', 'Business Services IT & Technology', 'Interested']
['Wed, 30 Sep - Sat, 03 Oct 2020', 'FinCon', 'Long Beach Convention & Entertainment Center, Long Beach 20.1 Miles from Los Angeles', 'FinCon will be helping financial influencers and brands create better content, reach their audience, and make more money. Collaborate with other influencers who share your passion for making personal finance...', 'Banking & Finance IT & Technology', 'Interested 7 following']
['Mon, 05  - Wed, 07 Oct 2020', 'NetDiligence Cyber Risk Summit', 'Loews Santa Monica Beach Hotel, Santa Monica 14.6 Miles from Los Angeles', 'NetDiligence Cyber Risk Summit will conference are attended by hundreds of cyber risk insurance, legal/regulatory and security/privacy technology leaders from all over the world. Connect with leaders in...', 'IT & Technology', 'Interested']

... etc.