0

複数のURLを処理する方法がわかりません。これは私がこれまでに試したことですが、リストから最後のURLを取得するだけです。

from twill.commands import *
from bs4 import BeautifulSoup
from urllib import urlopen

with open('urls.txt') as inf:
    urls = (line.strip() for line in inf)
    for url in urls:
        line = url 

site = urlopen(url)   

soup = BeautifulSoup(site)

for td in soup.find_all('td', {'class': 'subjectCell'}):
    print td.find('a').text
4

3 に答える 3

2

これらのコードはforループ内にある必要があります

site = urlopen(url)   

soup = BeautifulSoup(site)

for td in soup.find_all('td', {'class': 'subjectCell'}):
    print td.find('a').text

次に、各URLが呼び出されます。

于 2012-11-08T02:20:18.380 に答える
0

すべてのURLをループする場合は、各URLを処理するコードをループに入れる必要があります。しかし、あなたはそれをしていません。あなたが持っているのは:

for url in urls:
    line = url

これにより、変数がurl何度も再割り当てさlineれ、最終的に両方が最後のURLを指すようになります。そしてsize = urlopen(url)、ループの外側を呼び出すと、最後のURLで機能します。

これを試して:

with open('urls.txt') as inf:
    urls = (line.strip() for line in inf)
    for url in urls:
        site = urlopen(url)   
        soup = BeautifulSoup(site)
        for td in soup.find_all('td', {'class': 'subjectCell'}):
            print td.find('a').text
于 2012-11-08T02:11:28.363 に答える
0

各URLでやりたいことをすべてforループに入れる必要があります。

with open('urls.txt') as inf:
    urls = (line.strip() for line in inf)
    for url in urls:
        site = urlopen(url)   
        soup = BeautifulSoup(site)

        for td in soup.find_all('td', {'class': 'subjectCell'}):
            print td.find('a').text
于 2012-11-08T02:12:09.617 に答える