【问题标题】:How to use BeautifulSoup to scrape table links from reddit如何使用 BeautifulSoup 从 reddit 中抓取表格链接
【发布时间】:2019-08-14 14:56:22
【问题描述】:

我正在尝试使用 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 保持简单。

【问题讨论】:

  • 您在寻找 Imgur 图片的链接吗?

标签: python python-3.x beautifulsoup


【解决方案1】:

你几乎就在附近。您的 table_extract_items 是 HTML 锚点,您需要从中提取 text - 内容和属性 href 使用 [ ] 运算符。我想是不恰当的选择名称的选择混淆了你。 for-loop 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

检查一下:

In [40]: for anchor in table.findAll('a'):
        # if not anchor:
        #        continue
        href = anchor['href']
        text = anchor.text
        print (href, "--", text)
   ....:     
https://imgur.com/a/Y1WlDiK -- 6GB EVGA GTX 980 TI
https://imgur.com/gallery/yxkPF3g -- Intel i7-4790K
https://imgur.com/gallery/nUKnya3 -- Asus Z97-K Motherboard
https://imgur.com/gallery/9YIU19P -- 2x8 HyperX Fury DDR3 RAM
https://imgur.com/gallery/pNqXC2z -- Elagto HD 60 Pro Capture Card
https://imgur.com/gallery/5K3bqMp -- Samsung EVO 250 GB SSD
https://imgur.com/FO8JoQO -- Corsair Scimtar MMO Mouse
https://imgur.com/C8PFsX0 -- Corsair K70 RGB Rapidfire Keyboard
https://imgur.com/hfCEzMA -- I messed up

【讨论】:

    猜你喜欢
    • 2014-12-07
    • 2021-01-11
    • 2021-01-02
    • 2021-02-22
    • 2011-03-11
    • 2020-01-23
    • 1970-01-01
    相关资源
    最近更新 更多