简体   繁体   English

在 html 站点的 href 内提取 url

[英]Extracting url within href on html site

I have the following already extracted from web page:我已经从 web 页面中提取了以下内容:

 <a class="Directory-listLink" data-ya-track="todirectory" href="united-states/in">Indiana</a>,
 <a class="Directory-listLink" data-ya-track="todirectory" href="united-states/ia">Iowa</a>,
 <a class="Directory-listLink" data-ya-track="todirectory" href="united-states/ks">Kansas</a>,
 <a class="Directory-listLink" data-ya-track="todirectory" href="united-states/ky">Kentucky</a>,

I only want the href="united-states/il" part of each extracted.我只想要每个提取的href="united-states/il"部分。 Currently I am trying something like this:目前我正在尝试这样的事情:

for state in soup_state.find('a',href=True):
    print(state['href'])

I continually receive the error:我不断收到错误:

AttributeError: ResultSet object has no attribute 'find'. AttributeError:ResultSet object 没有属性“查找”。 You're probably treating a list of items like a single item.您可能将项目列表视为单个项目。 Did you call find_all() when you meant to call find()?当您打算调用 find() 时,您是否调用了 find_all()?

I want this to be ran in a for loop so I could get each state's url extracted, but am currently unable我希望它在 for 循环中运行,以便提取每个州的 url,但目前无法

I'm not sure how you got to soup_state , but try:我不确定您是如何到达soup_state的,但请尝试:

for state in soup_state:
     print(state['href'])

and see if it solves the problem.看看它是否能解决问题。

You can use a regular expression to find these contents.您可以使用正则表达式来查找这些内容。

import re

lines = ['<a class="Directory-listLink" data-ya-track="todirectory" href="united-states/in">Indiana</a>',
         '<a class="Directory-listLink" data-ya-track="todirectory" href="united-states/ia">Iowa</a>',
         '<a class="Directory-listLink" data-ya-track="todirectory" href="united-states/ks">Kansas</a>',
         '<a class="Directory-listLink" data-ya-track="todirectory" href="united-states/ky">Kentucky</a>']

for l in lines:
    print(re.search('href="[^"]*"',l).group())

This will give the output:这将给出 output:

href="united-states/in"
href="united-states/ia"
href="united-states/ks"
href="united-states/ky"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM