Python 链接抓取器

标签 python csv web-scraping beautifulsoup html-parsing

import requests    
from bs4 import BeautifulSoup    
data = requests.get("http://www.basketball-reference.com/leagues/NBA_2014_games.html")    
soup = BeautifulSoup(data.content)    
soup.find_all("a")    
for link in soup.find_all("a"):    
    "<a href='%s'>%s</a>" %(link.get("href=/boxscores"),link.text)

我试图仅获取盒子分数的链接。然后运行循环并将各个链接中的数据组织到 csv 中。我需要将链接保存为向量并运行一个循环......然后我陷入困境,我不确定这是否是正确的方法。

最佳答案

这个想法是迭代所有具有 href 属性的链接 (a[href] CSS Selector ),然后循环遍历链接和 construct an absolute link如果 href 属性值不以 http 开头。将所有链接收集到列表列表中并使用 writerows()将其转储到 csv:

import csv
from urlparse import urljoin

from bs4 import BeautifulSoup
import requests


base_url = 'http://www.basketball-reference.com'
data = requests.get("http://www.basketball-reference.com/leagues/NBA_2014_games.html")    
soup = BeautifulSoup(data.content)    

links = [[urljoin(base_url, link['href']) if not link['href'].startswith('http') else link['href']]
         for link in soup.select("a[href]")]

with open('output.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(links)

output.csv 现在包含:

http://www.sports-reference.com
http://www.baseball-reference.com
http://www.sports-reference.com/cbb/
http://www.pro-football-reference.com
http://www.sports-reference.com/cfb/
http://www.hockey-reference.com/
http://www.sports-reference.com/olympics/
http://www.sports-reference.com/blog/
http://www.sports-reference.com/feedback/
http://www.basketball-reference.com/my/auth.cgi
http://twitter.com/bball_ref
...

尚不清楚您的输出应该是什么,但这至少是您可以使用的起点。

关于Python 链接抓取器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27710483/

相关文章:

ruby - R 中 CAS 注册表到 Pubchem cid 标识符的转换

python - 如何使用 matplotlib 设置 x 轴的时间间隔,例如 15 分钟

javascript - 使用 Flask 提取 JavaScript 变量

python - python中的张量点运算

python - 从 CSV 文件中读取特定字段

mysql - 将 CSV 导入 MySQL - 偏移 1 列

python - 一种使用行和列标题读取 CSV 的 Pythonic 方法

python - 按行中非空元素的计数对 PySpark Dataframe 进行统一分区

javascript - 有没有办法在 nightjs 中处理弹出窗口

javascript - CRONTAB 执行 Python,使用 puppeteer 执行 Node 来进行网页抓取不起作用