gpt4 book ai didi

python - 从保存的 html 文件解析的 url 链接列表中解析标签的 url 链接。并将其全部保存在 csv 输出中

转载 作者:太空宇宙 更新时间:2023-11-03 18:05:41 24 4
gpt4 key购买 nike

如何从第 1 部分平滑过渡到第 2 部分并将结果保存在第 3 部分中?到目前为止,我还无法解析抓取的 url 链接,除非我自己将其插入到第 2 部分中。此外,我无法保存输出结果,因为最后一个 url 链接覆盖了所有其他链接。

import urllib
import mechanize
from bs4 import BeautifulSoup
import os, os.path
import urlparse
import re
import csv

第 1 部分:

path = '/Users/.../Desktop/parsing/1.html'

f = open(path,"r")
if f.mode == 'r':
contents = f.read()

soup = BeautifulSoup(content
search = soup.findAll('div',attrs={'class':'mf_oH mf_nobr mf_pRel'})
searchtext = str(search)
soup1 = BeautifulSoup(searchtext)

for tag in soup1.findAll('a', href = True):
raw_url = tag['href'][:-7]
url = urlparse.urlparse(raw_url)
p = "http"+str(url.path)

第 2 部分:

for i in url:
url = "A SCRAPED URL LINK FROM ABOVE"

homepage = urllib.urlopen(url)
soup = BeautifulSoup(homepage)

for tag in soup.findAll('a',attrs={'name':'g_my.main.right.gifts.link-send'}):
searchtext = str(tag['href'])
original = searchtext
removed = original.replace("gifts?send=", "")
print removed

第 3 部分

i = 0
for i in removed:
f = open("1.csv", "a+")
f.write(removed)
i += 1
f.close

更新1.经过建议后,我仍然得到这个: 回溯(最近一次调用最后一次): 文件“page.py”,第 31 行,位于 主页 = urllib.urlopen(url) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py”,第 87 行,位于 urlopen 返回 opener.open(url) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py”,第 180 行,打开 fullurl = 展开(toBytes(fullurl)) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py”,第 1057 行,在展开中 url = url.strip()AttributeError:“ParseResult”对象没有属性“strip”

最佳答案

在第 1 部分中,您不断用新 URL 覆盖 url。您应该使用一个列表并将 URL 附加到该列表中:

urls = []
for tag in soup1.findAll('a', href = True):
raw_url = tag['href'][:-7]
url = urlparse.urlparse(raw_url)
urls.append(url)
p = "http"+str(url.path) # don't know what that's for, you're not using it later

然后,在第 2 部分中,您可以直接迭代 url。同样,removed 不应在每次迭代中被覆盖。另外,不需要变量 original - 您的搜索文本不会被 replace 操作更改,因为它返回一个新字符串并保留原​​始字符串:

removed_list = []
for url in urls:
homepage = urllib.urlopen(url)
soup = BeautifulSoup(homepage)

for tag in soup.findAll('a',attrs={'name':'g_my.main.right.gifts.link-send'}):
searchtext = str(tag['href'])
removed = searchtext.replace("gifts?send=", "")
print removed
removed_list.append(removed)

然后,在第 3 部分中,您不必为要输出的每一行打开和关闭文件。事实上,您甚至没有正确关闭它,因为您没有调用 close() 方法。正确的方法是使用 with statement无论如何:

with open("1.csv", "w") as outfile:
for item in removed_list:
outfile.write(item + "\n")

虽然我不明白这是一个 CSV 文件(每行只有一项?)...

关于python - 从保存的 html 文件解析的 url 链接列表中解析标签的 url 链接。并将其全部保存在 csv 输出中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26955186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com