如何使用BeautifulSoup从Reddit抓取表格链接

时间:2019-03-24 00:25:26

标签: python python-3.x beautifulsoup

我正在尝试使用Beautiful Soup从Reddit表中抓取链接,并且可以成功提取该表中除URL之外的所有内容。我正在使用item.find_all('a'),但使用此代码时会返回一个空列表:

import praw
import csv
import requests
from bs4 import BeautifulSoup

def Authorize():
    """Authorizes Reddit API"""
    reddit = praw.Reddit(client_id='',
                     client_secret='',
                     username='',
                     password='',
                     user_agent='user')

url = 'https://old.reddit.com/r/formattesting/comments/94nc49/will_it_work/'
headers = {'User-Agent': 'Mozilla/5.0'}
page = requests.get(url, headers=headers)

soup = BeautifulSoup(page.text, 'html.parser')

table_extract = soup.find_all('table')[0]
table_extract_items = table_extract.find_all('a')

for item in table_extract_items:
    letter_name = item.contents[0]
    links = item.find_all('a')
    print(letter_name)
    print(links)

这是返回的内容:

6GB EVGA GTX 980 TI
[]
Intel i7-4790K
[]
Asus Z97-K Motherboard
[]
2x8 HyperX Fury DDR3 RAM
[]
Elagto HD 60 Pro Capture Card
[]

我希望在每个表行下方都有一个空白列表的URL。

我不确定这在构造上是否有所不同,但最终目标是提取所有表内容和链接(保持两者之间的关联)并保存为CSV作为两列。但是现在我只是想print保持简单。

1 个答案:

答案 0 :(得分:1)

您快到了。您的#default proxy stuff above... ProxyRequests off ProxyPass / http://localhost:5000/ #ProxyPass /static/ / ProxyHTMLURLMap http://localhost:5000/ / <Location /> ProxyPassReverse / ProxyHTMLEnable On ProxyHTMLURLMap / / RequestHeader unset Accept-Encoding </Location> <Location /static/ > ProxyPass ! </Location> 是HTML锚,您需要使用table_extract_items text运算符从中提取href –内容和属性[。我猜对变量名的不适当选择会使您感到困惑。 for循环]中的行是错误的!

这是我的解决方法:

links = item.find_all('a')
我的代码中的

for anchor in table.findAll('a'): # if not anchor: finaAll returns empty list, .find() return None # continue href = anchor['href'] print (href) print (anchor.text) 是您在代码中命名的table

检查此:

table_extract