【问题标题】:Scrape Href python刮 Href python
【发布时间】:2017-11-11 04:44:48
【问题描述】:

希望从某个站点抓取城市名称。这是我迄今为止编写的相关代码,文本存储在变量中。但是,我需要将所有城市名称放在一个列表中,这似乎对我不起作用。这是 HTML:

<a id="ctl00_ContentPlaceHolder1_rptrContinents_ctl00_rptrRows_ctl00_lnkBunker" href="PortDetails.aspx?ElementID=ffd65ee0-93ea-4195-b1ba-a69c8b1908c5">Amsterdam</a>

这是我的代码: 名称 = row.find_all('th')

column_1 = col[0].string.strip()
Ifo380.append(column_1)
column_2 = col[3].string.strip()
Ifo180.append(column_2)
column_3 = col[6].string.strip()
Mdo.append(column_3)
column_4 = col[9].string.strip()
Mgo.append(column_4)

for port in names:
name= item.contents.find_all("a").string

谁能帮忙?

【问题讨论】:

  • 完整的内容在哪里? column_x 是干什么用的?

标签: python beautifulsoup href screen-scraping


【解决方案1】:

你可以使用list comprehension

>>> html = '<a id="ctl00_ContentPlaceHolder1_rptrContinents_ctl00_rptrRows_ctl00_lnkBunker" href="PortDetails.aspx?ElementID=ffd65ee0-93ea-4195-b1ba-a69c8b1908c5">Amsterdam</a>'
>>> soup = BeautifulSoup(html)
>>> citynames = [names.text for names in soup.find_all('a')]
['Amsterdam']

【讨论】:

    【解决方案2】:

    假设您的 html 内容存储为:

    html_cont = '<a id="ctl00_ContentPlaceHolder1_rptrContinents_ctl00_rptrRows_ctl00_lnkBunker" href="PortDetails.aspx?ElementID=ffd65ee0-93ea-4195-b1ba-a69c8b1908c5">Amsterdam</a>'    
    

    然后你可以解析它并将城市添加到列表中:

    soup = BeautifulSoup(html_cont, "lxml")
    
    city_names = []
    for link in soup.find_all('a', href=True):
        city_names.append(link.text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      相关资源
      最近更新 更多