【问题标题】:Downloading target link html in a text file (Beautiful Soup - Python3)在文本文件中下载目标链接 html (Beautiful Soup - Python3)
【发布时间】:2016-11-06 03:00:11
【问题描述】:

我对 python 和学习网络爬虫完全陌生。

我正在尝试下载文本页面中的单个目标链接。
到目前为止,我成功提取了我需要的所有目标 URL,但不知道如何下载文本文件中的所有目标 HTML 文本。

谁能给我一个大致的想法。

url = ""
r  = requests.get(url)
data = r.text
soup = BeautifulSoup(data, "lxml")
link1 = soup2.find_all('a', href=re.compile("drupal_lists"))
for t in link1:
    print(t.attrs['href'])

【问题讨论】:

    标签: python beautifulsoup web-crawler


    【解决方案1】:

    在您的 for 循环中,使用 requests 库访问链接 url 并将内容写入文件。比如:

    link_data = requests.get(t.attrs['href']).text
    with open('file_to_write.out', 'w') as f:
      f.write(link_data)
    

    您可能希望更改每个链接的文件名。

    【讨论】:

    • 我添加了这个for语句,但它不起作用。它只显示一个目标链接。这里有什么问题?对于链接 1 中的 t:link_data = requests.get(t.attrs['href']).text with open('text.txt', 'w') as f: f.write(link_data)
    猜你喜欢
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多