【问题标题】:Scrape a list of numbers from the source code of a webpage in Python and output to text file从 Python 中的网页源代码中抓取数字列表并输出到文本文件
【发布时间】:2015-09-19 13:43:00
【问题描述】:

我是一个 3 天大的 Python 用户。

  1. 我想让程序读取网站源代码

  2. 然后只复制出现在= 符号之后的一组数字,仅用于类似
    <a href="mypage.php?REF=2327327"></a>

  3. 的链接
  4. 然后我想将它们放在一个列表中(在后续代码块中),该列表将从该列表中获取每个数字

  5. 并将列表中的每个数字放入模板段落中。

  6. 那我想把这样的段落输出到一个文本文件中。

想要的输出是

5646556
6564654
454654
4646546

等等

这是我正在使用的代码。

from bs4 import BeautifulSoup
import urllib2
import re

url = "somewebsite"

headers = { 'User-Agent' : 'Mozilla/5.0' }
html = urllib2.urlopen(urllib2.Request(url, None, headers)).read()
soup = BeautifulSoup(html)

links = soup.findAll('a', href=re.compile('.*mypage\.php\?REF=[0-9]*'))
template = """lasljasfkljaslkfj{}
slajfljasflk
aslkjfklasjflkasjf
alksjflkasjf;lk
"""

replace = [ link.split("=")[1] for link in links ]

output = [template.format(r) for r in replace]

print output
with open('output.txt', 'w') as f_output:
    f_output.write(''.join([template.format(r) for r in replace]))

这是原始程序的另一半。 这个程序只从你必须输入的列表中获取数字,并将这些数字中的每一个放在一个段落中,然后复制该段落,并从列表中插入下一个数字。

template = """fjajflakjfakjfl;kj REF={}
sklkasalsjklas
klajsl;kdajs;djas
aksljl;askjflka
"""

replace = [1131062,
    1140921,
1141326,
1141355,
1141426,
1141430,
1141461,
1141473,
1141477,
1141502,
1141525,
1141622,
1141662,
757053,
989967]

output = [template.format(r) for r in replace]

with open('output.txt', 'w') as f_output:
    f_output.write(''.join([template.format(r) for r in replace]))

【问题讨论】:

  • 打破你的句子。很难理解你想要实现什么?
  • @AhsanulHaque7 我在问题中添加了休息

标签: python beautifulsoup


【解决方案1】:

要获取数字,只需使用 split

st = "mypage.php?REF=23273273"

_, number = st.split('=')

print(number)

23273273

【讨论】:

  • 你的答案似乎是正确的。但是请告诉我把它放在我的代码中的什么地方?你能把它复制粘贴到正确的地方然后写吗?泰。
【解决方案2】:

首先,您应该查看我对您最后一个问题here 的更新答案,因为如果您不这样做,此代码将抛出与我们之前讨论过的相同的错误。这将正确地为您提供replace 列表的值。您的output 分配也可以正常工作,但是当您尝试加入所有段落时,它们会一起运行。您应该使用换行符 (\n) 加入它们。这意味着你的代码的最后一部分应该是这样的:

template = """lasljasfkljaslkfj{}
slajfljasflk
aslkjfklasjflkasjf
alksjflkasjf;lk
"""

replace = [ link['href'].split("=")[1] for link in links ] # note the added ['href']

output = [ template.format(r) for r in replace ]

with open('output.txt', 'w') as f_output:
    f_output.write('\n'.join(output)) # we don't need to re-make the list, and join on \n

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多