python - 网页抓取到数据框
问题描述
我是 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
解决方案
我在第一个代码块的“行”中添加了一个检查是否有信息。
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
这似乎有效。
推荐阅读
- python - 打开 CV 无法从 URL 读取图像
- boolean-logic - 如果 p → q 那么 q → p?
- laravel - 如何在数据表 Laravel 8 中添加按钮以打开带有参数的 url
- cmake - 使用 CMake FetchContent 时的目标冲突
- c# - Azure appservice 返回错误 500.30,但我的应用在 kudu (ASP.NET Core) 上运行良好
- javascript - 为什么 CSS 类未应用于复选框?
- javascript - php/html - 如果新标签已经存在,不要创建新标签
- python - 如何为这样的功能使用for循环?
- python - 正则表达式返回空值
- xslt-2.0 - XSLT - 在复制所有其他元素时向元素添加序列号/计数器