【问题标题】:WebScraper cannot access fileWebScraper 无法访问文件
【发布时间】:2020-03-19 03:20:21
【问题描述】:

所以我正在关注这个关于使用 Python 进行 Webscraping 的教程。每当我运行代码时都会遇到此错误

FileNotFoundError: [Errno 2] No such file or directory: './data/nyct/turnstile/turnstile_200314.txt'

我有一种预感,这意味着 webscraper 无法访问该文件,但是当我检查 HTML 时,该文件存在。请帮忙。 这是我的参考代码:

import requests
import urllib.request
import time
from bs4 import BeautifulSoup

#Set URL you want to webscrape from
url = 'http://web.mta.info/developers/turnstile.html'

#Connect to URL
response = requests.get(url)

#Parse HTML and save to BeautifulSoup object
soup = BeautifulSoup(response.text,'html.parser')

#Loop to download whole dataset
linecount = 1 #var to track current line

for onetag in soup.findAll('a'):
    if linecount>=36:
        link = onetag['href']
        downloadurl = 'http://web.mta.info/developers/'+link
        urllib.request.urlretrieve(downloadurl,'./'+link[link.find('/turnsttile_')+1:])
        time.sleep(3)#pause code so as to not get flagged as spammer

    #increment for next line
    linecount+=1

【问题讨论】:

  • 该错误与从网站读取无关;在您的系统上写入.txt 文件有困难。 data/nyct/turnstile 目录是否与脚本位于同一目录中?
  • 我没有创建一个目录,我假设我正在提取的文件将被发送到那里。抱歉,我对此很陌生,请您详细说明一下。
  • 抱歉,“将被发送到那里”是什么意思?您的代码从 URL 下载,然后将其保存到本地文件。如果要在该目录下保存文件,则必须已创建该目录。
  • 所以由于没有data/nyc/turnstile文件目录,所以基本上代码无法保存文件?
  • 请提供完整的错误信息。顺便说一句,您应该将response.content 的结果传递给BeautifulSoup(),而不是response.text。另外,为什么同时使用 requests 和 urllib.request?

标签: python web web-scraping


【解决方案1】:

将以下脚本放在一个文件夹中并运行它。确保调整这部分 [:2] 以满足您的需要,因为我将其定义为测试:

import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

url = 'http://web.mta.info/developers/turnstile.html'
base = 'http://web.mta.info/developers/'

response = requests.get(url)
soup = BeautifulSoup(response.text,'html.parser')
for tag in soup.select('a[href^="data/nyct/"]')[:2]:
    filename = tag['href'].split("_")[1]
    with open(filename,"wb") as f:
        f.write(requests.get(urljoin(base,tag['href'])).content)

如果你想坚持.find_all(),你可以这样做来达到同样的效果:

for onetag in soup.find_all('a',href=True):
    if not onetag['href'].startswith('data/nyct/'):continue
    link = urljoin(base,onetag['href'])
    print(link)

或者像这样:

for onetag in soup.find_all('a',href=lambda e: e and e.startswith("data/nyct/")):
    link = urljoin(base,onetag['href'])
    print(link)

【讨论】:

  • 谢谢!这行得通,您介意解释您所做的更改以及它们如何使代码工作吗?再次感谢您的帮助!
  • 查看this link 以获得清晰。
猜你喜欢
  • 2021-10-19
  • 2020-11-19
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多