首页 > 解决方案 > 网页抓取到数据框

问题描述

我是 Beautiful Soup 的新手,并试图抓取https://10times.com/losangeles-us/technology/conferences并提取事件数据及其相关链接。

我已经设法抓取事件数据及其链接,但是在组合到数据框时,我正在努力让正确的事件与正确的事件链接对齐。我已经尝试删除空结果,但是,我无法弄清楚。

这是我提取数据的代码

import bs4 as bs
import urllib.request

source = urllib.request.urlopen('https://10times.com/losangeles-us/technology/conferences').read()
soup = bs.BeautifulSoup(source,'html.parser')

table = soup.find('tbody')

table_rows = table.find_all('tr')#find table rows (tr)


arr=[]
for tr in table_rows:   
    td = tr.find_all('td')  #find all the table data
    row = [tr.text for tr in td]
    arr.append(row) #This line > https://stackoverflow.com/questions/50633050/scrape-tables-into-dataframe-with-beautifulsoup    
df = pd.DataFrame(arr, columns=['Date', 'Event Name', 'Venue', 'Description', 'Type', 'Unnamed:'])
df.columns = ['Date', 'Event Name', 'Venue', 'Description', 'Type', 'Interested/Following Count'] 
df.dropna()
df

这是我提取链接的代码

arr2 = []
#finds <h2's>
h2s = soup.find_all('h2')
for h2 in h2s:
    links = h2.a['href']
    arr2.append(links)
df2 = pd.DataFrame(arr2)
df2.columns = ['Links'] 
df2.dropna()

这是我将事件数据 + 链接组合到一个数据框中的 2 次尝试,但是,链接与正确的事件不匹配。

from pandas import *

df3 = pd.concat([df,df2],sort=False, axis=1)
df3
#df3.to_html('test1.html')

试图放弃无

df.dropna()
df3 = pd.concat([df,df2], sort=False, axis=1)
df3 = df3.replace(to_replace='None', value=np.nan).dropna()
df3

标签: pythonpandasbeautifulsoup

解决方案


我在第一个代码块的“行”中添加了一个检查是否有信息。

import bs4 as bs
import urllib.request

source = urllib.request.urlopen('https://10times.com/losangeles-us/technology/conferences').read()
soup = bs.BeautifulSoup(source,'html.parser')

table = soup.find('tbody')

table_rows = table.find_all('tr')#find table rows (tr)


arr=[]
for tr in table_rows:   
    td = tr.find_all('td')  #find all the table data
    row = [tr.text for tr in td]
    if len(row) > 1:
        arr.append(row) #This line > https://stackoverflow.com/questions/50633050/scrape-tables-into-dataframe-with-beautifulsoup    
df = pd.DataFrame(arr, columns=['Date', 'Event Name', 'Venue', 'Description', 'Type', 'Unnamed:'])
df.columns = ['Date', 'Event Name', 'Venue', 'Description', 'Type', 'Interested/Following Count']
df

这似乎有效。


推荐阅读