1

私は次のコードを持っています:

import re
from bs4 import BeautifulSoup

f = open('AIDNIndustrySearchAll.txt', 'r')
g = open('AIDNurl.txt', 'w')
t = f.read()
soup = BeautifulSoup(t)

list = []
counter = 0

for link in soup.find_all("a"):
    a = link.get('href')
    if re.search("V", a) != None:
        list.append(a)
        counter = counter + 1

new_list = ['http://www.aidn.org.au/{0}'.format(i) for i in list]
output = "\n".join(i for i in new_list)

g.write(output)

print output
print counter

f.close()
g.close()

基本的には、保存されたHTMLページを調べて、興味のあるリンクを取得します。Pythonは初めてなので、コードはひどいものですが、(ほぼ)機能しています;)

現在の問題は、各リンクの1つではなく2つのコピーを返すことです。ループの設定方法と関係があると思いますが、少し行き詰まっています。

この質問に関するヘルプ(必要に応じて、HTMLや探しているリンクに関する詳細情報など)や一般的なコードの改善を歓迎します。これにより、可能な限り多くのことを学ぶことができます。

4

3 に答える 3

2

あなたもコードの最適化を求めているので、私は私の提案を答えとして投稿します。お気軽に!

from bs4 import BeautifulSoup

f = open('AIDNIndustrySearchAll.txt', 'r')
t = f.read()
f.close()

soup = BeautifulSoup(t)
results = []   ## 'list' is a built-in type and shouldn't be used as variable name

for link in soup.find_all('a'):
    a = link.get('href')
    if 'V' not in a:
        results.append(a)

formatted_results = ['http://www.aidn.org.au/{0}'.format(i) for i in results]
output = "\n".join(formatted_results)

g = open('AIDNurl.txt', 'w')
g.write(output)
g.close()

print output
print len(results)

これでも元の問題は解決しません。私や他の人々の質問コメントを参照してください。

于 2012-11-14T10:40:50.817 に答える
2

他の人がコメントで指摘したように、ループは問題ないように見えるので、繰り返しは HTML 自体にある可能性があります。HTML ファイルへのリンクを共有していただければ、さらにお役に立てるかもしれません。

一般的なコードの改善については、次のようにアプローチします。

from bs4 import BeautifulSoup
soup = BeautifulSoup(open('AIDNIndustrySearchAll.txt', 'r'))

# create a generator that returns actual href entries
links = (x.get('href') for x in soup.find_all('a'))

# filter the links to only those that contain "V" and store it as a 
# set to remove duplicates
selected = set(a for a in links if "V" in a)

# build output string using selected links
output = "\n".join('http://www.aidn.org.au/{0}'.format(a) for a in selected)

# write the string to file
with open('AIDNurl.txt', 'w') as f:
  f.write(output)

print output
print len(selected)  # print number of selected links
于 2012-11-14T11:43:28.437 に答える
0

Find_all は、すべての要素のリストを返します。最初のものだけが必要な場合は、次のようにすることができます for link in soup.find_all("a")[:1]:。リストがリンクのコピーである理由は明確ではありません。print ステートメントを使用して、コードをより深く理解することができます。リストとリストの長さなどを出力します。または、pdbを使用できます

于 2012-11-14T10:38:09.907 に答える