在Python中从HTML获取每秒钟一个URL

2024-06-17 07:52:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力从网站上刮网址的。我想搜集的网站的HTML代码是:

<tr>
        <td>
            <span>

    <table class="search-result-ad-row" cellspacing="3" border="0">
    <tbody>
        <tr>
            <td class="picture" rowspan="2"><a title="3.izbový byt v starom meste na ulici Kpt. Nálepku" href="inzerat/RE0005055-16-000281/3-izbovy-byt-v-starom-meste-na-ulici-kpt-nalepku"><img src="/data/189/RE0005055/ads/195/RE0005055-16-000281/img/thum/37587134.jpeg" alt=""/></a>
            </td>
            <td class="title" colspan="2"><a title="3.izbový byt v starom meste na ulici Kpt. Nálepku" href="inzerat/RE0005055-16-000281/3-izbovy-byt-v-starom-meste-na-ulici-kpt-nalepku"><h2 style="font-size: inherit;">3.izbový byt v starom meste na ulici Kpt. Nálepku</h2></a>
                <span></span>
            </td>
        </tr>
        <tr>

我想通过使用以下python代码获得href

br = mechanize.Browser()
br.open("http://www.reality.sk/")
br.select_form(nr=0)
br["tabs:scrn243:scrn115:errorTooltip.cityName:cityName"]="poprad"
br.submit()

def hello():
    soup = BeautifulSoup(br.response().read())
    for link in soup.findAll('a'):
        link2 = link.get('href')
        if "inzerat/" in link2:
            print 'http://www.reality.sk/' + link.get('href')

但问题是,每个URL有2个结果(因为有2个href属性)。我试过使用table标签,带有class属性的td标签(picture或title)或者甚至使用rowspan(=2)来刮取。但是我没有得到想要的结果。我不知道如何使代码工作。你知道吗


Tags: 代码brtitletrclasstdhrefspan
1条回答
网友
1楼 · 发布于 2024-06-17 07:52:39

我猜您在使用class选择器查找时遇到了问题。此外,您还可以链接find返回的标记-请查看此解决方案是否有帮助(我不能100%确定这是否是您想要实现的目标):

soup.find_all('table', class_='search-result-ad-row')
for ad_table in soup.find_all('table', class_='search-result-ad-row'):
    print ad_table.find(class_='picture').find('a').attrs['href']

相关问题 更多 >