【问题标题】:How to open multiple TXT files under for loop and assigning a names to each file如何在for循环下打开多个TXT文件并为每个文件分配一个名称
【发布时间】:2020-03-03 06:48:57
【问题描述】:

我首先尝试抓取包含不同工作名称(带有链接)的td。我想将我将再次从那些“td”链接(来自他们网页的相应工作的数据)中刮取的数据保存在不同的 txt 文件中。我希望将每个网页的抓取数据分别保存在不同的 txt 文件中。我可以这样做吗?如果您对此有所了解,请分享您的想法!

import requests
from bs4 import BeautifulSoup

main = "https://deltaimmigration.com.au/Australia-jobs/"

def First():
    r = requests.get(main)
    soup = BeautifulSoup(r.text, 'html5lib')
    links = []
    with open("links.txt", 'w', newline="", encoding="UTF-8") as f:
        for item in soup.findAll("td", {'width': '250'}):
            item = item.contents[1].get("href")[3:]
            item = f"https://deltaimmigration.com.au/{item}"
            f.write(item+"\n")
            links.append(item)
    print(f"We Have Collected {len(links)} urls")
    return links

def Second():
    links = First() 
    with requests.Session() as req:
        for link in links:
            print(f"Extracting {link}")
            r = req.get(link,timeout = 100)
            soup = BeautifulSoup(r.text, 'html5lib')
            for item in soup.findAll("table", {'width': '900'}):
                return item

def Third():
    r = requests.get(main)
    soup = BeautifulSoup(r.text, 'html5lib')
    result = Second()
    for item in soup.findAll("td", {'width': '250'}):
        with open(item.text + '.txt', 'w', newline="", encoding="UTF-8") as f:
            f.write('result')           

Third()       

我尝试了以下方法:

with open(item.text + '.txt', 'w', newline="", encoding="UTF-8") as f:

但我遇到了错误

File "e:/test/check.py", line 10, in Third with open(item.text + '.txt', 'w', newline="", encoding="UTF-8") as f: FileNotFoundError: [Errno 2] No such file or directory: ' Vegetable Grower (Aus)/market Gardener (NZ).txt'"

【问题讨论】:

  • 好吧,显然您需要从链接中下载数据,因此您需要在循环中为每个链接执行requests.get。此外,'{item}.txt' 将不起作用 - 如果您的 Python 至少为 3.6,f'{item}.txt' 将起作用,否则使用 item + '.txt'...
  • @Błotosmętek 实际上是 item.text
  • @xxMrPHDxx 准确的意思是“不会按预期工作”,因为每次都会使用相同的文件名,从而破坏文件的先前内容。
  • @Błotosmętek 不,我的意思是item.text + '.txt' 因为itemobject,而不是str
  • 编辑您的问题并包含更多详细信息以便能够理解您的问题。

标签: python beautifulsoup


【解决方案1】:
import requests
from bs4 import BeautifulSoup

main = "https://deltaimmigration.com.au/Australia-jobs/"


def First():
    r = requests.get(main)
    soup = BeautifulSoup(r.text, 'html5lib')
    links = []
    names = []
    with open("links.txt", 'w', newline="", encoding="UTF-8") as f:
        for item in soup.findAll("td", {'width': '250'}):
            name = item.contents[1].text
            item = item.contents[1].get("href")[3:]
            item = f"https://deltaimmigration.com.au/{item}"
            f.write(item+"\n")
            links.append(item)
            names.append(name)
    print(f"We Have Collected {len(links)} urls")
    return links, names


def Second():
    links, names = First()
    with requests.Session() as req:
        for link, name in zip(links, names):
            print(f"Extracting {link}")
            r = req.get(link)
            soup = BeautifulSoup(r.text, 'html5lib')
            for item in soup.findAll("table", {'width': '900'}):
                with open(f"{name}.txt", 'w', newline="", encoding="UTF-8") as f:
                    f.write(item.text)


Second()

【讨论】:

  • 我尝试了您的答案,其中我还将超时分配给了 100,但是我遇到了类似“无法建立新连接:[WinError 10060] 连接尝试失败,因为连接方没有一段时间后没有正确响应,或者由于连接的主机未能响应而建立连接失败'))".....你知道为什么吗??
  • 我昨天在你的另一个帖子上回复了同样的问题,但看起来你只是忽略并再次询问。
  • 不,我尝试同时分配超时和代理....但是在抓取了几个链接后我得到了同样的错误!!
  • @BidhyaPokharel 我已经测试了一段时间的代码。看起来问题出在你的最后。 pasteboard.co/IXniyX3.png
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多