【发布时间】: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'因为item是object,而不是str -
编辑您的问题并包含更多详细信息以便能够理解您的问题。
标签: python beautifulsoup